1、官网文档阐明:https://cn.vuejs.org/v2/api/#Vue-use
2、找到源码看
Vue.use(plugin)
这个plugin,要么是蕴含install办法的对象,要么自身就是一个函数。第一个参数始终是Vue对象。
function initUse (Vue) {
Vue.use = function (plugin) {
var installedPlugins = (this._installedPlugins || (this._installedPlugins = []));
if (installedPlugins.indexOf(plugin) > -1) { // 判断插件有没有被注册
return this
}
// additional parameters
var args = toArray(arguments, 1);
args.unshift(this); //this 指向 Vue 对象,所以数组参数第一个始终是vue对象
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args); // 整顿好的数组参数传给install办法,this指向为plugin本人
} else if (typeof plugin === 'function') {
plugin.apply(null, args); // plugin是函数的话 ,间接调用,传入参数。留神:其内this为null
}
installedPlugins.push(plugin);
return this
};
}
/**
* Convert an Array-like object to a real Array.
*/
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
}
3、通过下面可知编写插件的两种办法,应用:
1)、蕴含install办法的对象(举荐),逻辑性比拟强的比拟适宜, 编写灵便,拓展性也高, 最初通过install办法裸露给Vue对象
const plugin = {
//this 指向plugin对象自身
install() {
// 巴拉巴拉一系列操作
let conso = this.handleConsole()
console.log(this.handleConsole)
console.log(conso)
console.log(this.data)
},
handleConsole() {
console.log('handleConsole');
let comdata = '吃葡萄不吐葡萄皮'
return comdata
},
data: [1,2,3]
}
export default plugin
浏览器打印:
2)、一个函数,适宜一般简略的
// 比方自定义全局组件,对立一个文件
// globalComponents.js
import Vue from 'vue';
import pHeader from './components/pheader'
import pFooter from './components/pfooter'
function plugin() {
//this 为null
Vue.component('pHeader', pHeader);
Vue.component('pFooter', pFooter);
}
export default plugin
//应用 main.js
import Vue from 'vue'
import GlobalComponents from './globalComponents'
Vue.use(GlobalComponents);
// 而后就能够全局应用自定义的组件了。
4、还有个问题:
该办法须要在调用 new Vue() 之前被调用。那么为什么要在之前调用的?
简略的了解:如果在new Vue() 之后调用,那么你的插件的内容就来不及增加到Vue中。
发表回复