1.官方文档说明:https://cn.vuejs.org/v2/api/#Vue-use2。找到源码看看插件Vue.use(plugin),或者是包含install方法的对象,或者本身就是一个函数。第一个参数总是一个Vue对象。functioninitUse(Vue){Vue.use=function(plugin){varinstalledPlugins=(this._installedPlugins||(this._installedPlugins=[]));if(installedPlugins.indexOf(plugin)>-1){//判断插件是否注册returnthis}//附加参数varargs=toArray(arguments,1);args.unshift(这个);//this指向Vue对象,所以第一个数组参数总是vue对象if(typeofplugin.install==='function'){plugin.install.apply(plugin,args);//排列好的数组参数传给install方法,this指向插件本身}elseif(typeofplugin==='function'){plugin.apply(null,args);//如果插件是函数,直接调用并传入参数。注意:这是null}installedPlugins.push(plugin);returnthis};}/***将类数组对象转换为真正的数组。*/functiontoArray(list,start){开始=开始||0;vari=list.length-开始;varret=新数组(i);while(i--){ret[i]=list[i+start];}returnret}3、从上面两种方法写插件,使用:1)、包含install方法的对象(推荐),逻辑的比较合适,写法灵活,扩展性也高,最后通过install方法暴露给Vue对象constplugin={//this指向插件对象本身install(){//巴拉巴拉系列操作letconso=this.handleConsole()console.log(this.handleConsole)console.log(conso)console.log(this.data)},handleConsole(){console.log('handleConsole');letcomdata='吃葡萄不吐葡萄皮'returncomdata},data:[1,2,3]}exportdefaultpluginbrowserprint:2),一个函数,适合普通简单//比如自定义全局组件,统一一个文件//globalComponents.jsimportVuefrom'vue';importpHeaderfrom'./components/pheader'importpFooterfrom'./components/pfooter'functionplugin(){//thisisnullVue.component('pHeader',pHeader);Vue.component('pFooter',pFooter);}exportdefaultplugin//usemain.jsimportVuefrom'vue'importGlobalComponentsfrom'./globalComponents'Vue.use(GlobalComponents);//然后就可以全局使用自定义组件了4.还有一个问题:这个方法需要在调用newVue()之前调用。那为什么叫之前呢?简单理解:如果在newVue()之后调用,那么你插件的内容就来不及添加到Vue中了。
