Vue 自定义一个插件的用法及案例

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>
 

猜你喜欢

转载自www.cnblogs.com/kaiqinzhang/p/9962669.html