原文地址:lastingman.com/2019/06/05/…vue
Vue.prototype
來實現。在開發項目的時候,咱們通常都用 vue-cli 來避免繁瑣的 webpack 配置和 template 配置。可是官方 cli3 如今並不支持搭建 plugin 開發的項目。node
還好,已經有大神(Kazupon)走在了咱們前面,咱們就用現成的 vue-cli-plugin-p11n。webpack
若是你沒有安裝 vue-cli,請先安裝git
npm i -g @vue/cli
複製代碼
首先,搭建項目github
vue create [your plugin name] && cd [your plugin name]
vue add p11n
複製代碼
這樣咱們就有了一個初始化的插件開發環境。web
開發 vue 插件其實就是寫一個 install 方法,而後把這個方法暴露出來給你的用戶,他們就能夠用Vue.use(plugin)
載入插件了。vue-cli
借用 vue 官方 API 上的解釋: 若是插件是一個對象,必須提供 install 方法。若是插件是一個函數,它會被做爲 install 方法。install 方法調用時,會將 Vue 做爲參數傳入。 該方法須要在調用
new Vue()
以前被調用。 當 install 方法被同一個插件屢次調用,插件將只會被安裝一次。npm
export const install = function (Vue, options) {
// Vue 就是 vue 實例
// options 就是 Vue.use(plugin,options) 傳入的第二個參數 options
// 1. 添加全局方法或屬性
Vue.myGlobalMethod = function () {
// 邏輯...
}
// 2. 添加全局資源
Vue.directive('my-directive', {
bind (el, binding, vnode, oldVnode) {
// 邏輯...
}
...
})
// 3. 注入組件選項
Vue.mixin({
created: function () {
// 邏輯...
}
...
})
// 4. 添加實例方法
Vue.prototype.$myMethod = function (methodOptions) {
// 邏輯...
}
}
複製代碼
p11n 已經幫助咱們部署好了大部分 package.json 配置,只須要本身填寫好 name,author,license,repository,description,keywords 這幾個選項就能夠了。json
# login npm
npm login
# patch version
npm version patch
# publish
npm publish --access public
複製代碼
我本身寫了一個很是簡單的插件 vue-chart,能夠做爲參考。bash