vue中实现自定义插件

给每个组件增加$eventBus的插件功能

函数里面必须有install函数,在main.js中要声明的话就要加static,再在项目中通过Vue.use()使用,所定义的插件相当于use这个函数的一个参数。下面了解下Vue.use主要干了什么。先看看Vue.use得源码:

Vue.use = function (plugin) {
 /* istanbul ignore if */
  if (plugin.installed) {
    return
  }
  // additional parameters
  var args = toArray(arguments, 1);
  args.unshift(this);
  if (typeof plugin.install === 'function') {
    plugin.install.apply(plugin, args);
  } else if (typeof plugin === 'function') {
    plugin.apply(null, args);
  }
  plugin.installed = true;
  return this
};

当插件install后就会设置plugin.installed = true;,对应如果已经install了就回直接return

if (plugin.installed) { return }

使用use的目的就是要执行plugin中的install函数。我们在使用Vue.use的时候,第一个参数传的时plugin本身,后面传的才是需要的参数,所有就有了如下的toArray的参数构造。作用就是把类数组(参数:arguments),剔除第一个参数plugin本身后,转化为真正的数组。

function toArray (list, start) {
  start = start || 0;
  var i = list.length - start;
  var ret = new Array(i);
  while (i--) {
    ret[i] = list[i + start];
  }
  return ret
}

接下来:args.unshift(this);把this插入数组最前面(此处是Vue.use调用,所以this指向Vue),相当于[Vue, …]。之后执行install函数,判断plugin.install是函数则执行plugin.install,plugin本身是函数则执行plugin。最后设置plugin.installed = true;避免重复执行。

if (typeof plugin.install === 'function') {
  plugin.install.apply(plugin, args);
} else if (typeof plugin === 'function') {
  plugin.apply(null, args);
}
plugin.installed = true;
let VueClass=null
export default class Plugin {
     static install(Vue,options){
        VueClass=vue
     }
     constructor(){
        const eventBus=VueClass&& new VueClass()
        VueClass && VueClass.minxin({
           created(){
             if(this.$root.$options.plugin){
                this.$eventBus=eventBus
             }else{
             }
           }
        })
     }
}

if判断new Vue()中是否激活调用,如果没被调用的话就不会触发this.$eventBus


import Vue from 'Vue'
import App from './App.vue'
import store from  './store'
import router from './router'
import Plugin from './plugin'

Vue.use(Plugin)
const plugin=new Plugin()
Vue.config.productionTip=false
new Vue({
   store,
   router,
   ...
})
<template>
  <div>
     <input type="text" v-model="value">
     <button @click="addAction">添加</button>
  </div>
</template>
<script>
export default{
    data(){
      return{
        value:''
      }
    },
    methods:{
       addAction(){
         console.log(this.$eventBus)
       }
    }
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值