vue的插件通常是用來添加全局功能,
插件按功能分一般有:
- 1、添加全局方法或屬性
- 2、添加全局屬性:指令、過濾器、過渡
- 3、通過全局混入來添加一些組件選項
- 4、添加 Vue 實例方法,通過把它們添加到 Vue.prototype 上實現
使用插件
1、使用import引入插件
2、Vue.use(插件名稱)
開發插件
Vue.js 的插件應該暴露一個 install 方法。這個方法的第一個參數是 Vue 構造器,第二個參數是一個可選的選項對象:
MyPlugin.install = function (Vue, 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) {
// 邏輯...
}
}
開發一個簡單的插件
- 1、開發插件
// justs.js
function install() {
console.log("進入插件~")
}
export default { install }
- 2、引用插件
// 在main.js中引入
import Justs from './plugins/justs'
Vue.use(Justs)
- 3、一個最簡單的插件就開發完成了