Vue 自定義一個外掛的用法及案例
阿新 • • 發佈:2018-11-15
1.開發外掛
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) {
// 邏輯...
}
}
2.外掛的使用
通過全域性方法 Vue.use() 使用外掛。它需要在你呼叫 new Vue() 啟動應用之前完成:
// 呼叫 `MyPlugin.install(Vue)`
Vue.use(MyPlugin)
//也可以傳遞引數:
Vue.use(MyPlugin, { someOption: true })
new Vue({
//... options
})
3.案例:給字型新增顏色
重點:先定義一個MyPlugin物件,這個Vue官網中沒有寫,需要特別注意。
let MyPlugin = {}
MyPlugin.install = function (Vue, options) {
Vue.directive('color', function (el, binding) {
el.style.color = binding.value || options.x
})
}
Vue.use(MyPlugin, { x: 'red' })
const vm = new Vue({
el: '#root'
})
<div v-color="'blue'">hello</div>