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.案例1:给字体添加颜色
重点:先定义一个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>
 
4.案例2:在项目中使用插件
在图片加载出来之前,给一个随机的背景颜色。
1.建一个文件plugin.js     写好插件并暴露
let MyPlugin = {}
MyPlugin.install = function (Vue, options) {
Vue.directive('img',{
inserted(el,binding){
var color = Math.floor(Math.random()*1000000);
el.style.backgroundColor = "#"+color;
var img = new Image();
img.src = binding.value;
img.onload = function(){
el.src = binding.value;
}
}
})
}
export default MyPlugin
 
之后在main.js文件中引入
import MyPlugin from 'utils/plugin'
Vue.use(MyPlugin)
 
大功告成!