用法
在我的项目中咱们常常应用到Vue.use,比方Vue.use(ElementUI),Vue.use(vueRouter),那么咱们来看一看Vue的应用办法。
Vue.use接管的是一个函数或者是一个对象,如果曾经注册过此插件了那么就不会再进行注册
1.如果传进来的是对象的话,这个对象外面蕴含一个install办法那么间接让install这个函数执行并且将这个对象作为install中的this让install执行,而后将Vue和其余定义的参数作为参数传递给install函数
let a ={
install(Vue,a,b){
console.log(Vue,a,b,this);
}
}
Vue.use(a,1,2)
2.如果传进来的是函数的话那么间接让这个函数执行,并且让null作为这个函数的this(也就是将window作为这个函数的this),而后将Vue和其余定义的参数作为参数传递给install函数
function a(Vue,a,b){
console.log(Vue,a,b,this);
}
Vue.use(a,1,2)
Vue.use源码
import { toArray } from '../util/index'
export function initUse (Vue: GlobalAPI) {
//承受的是函数或者对象
Vue.use = function (plugin: Function | Object) {
const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
//installedPlugins缓存机制,如果存在那么间接return
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
//将传进来的自定义参数转换成数组
const args = toArray(arguments, 1)
//将Vue当做第一个参数,比方install(Vue)这里能间接能拿到Vue
args.unshift(this)
//如果是对象的话,外面会有一个install函数
if (typeof plugin.install === 'function') {
//间接执行并将这个对象作为函数的this,并将参数传过来
plugin.install.apply(plugin, args)
//如果传进来的是一个函数的话
} else if (typeof plugin === 'function') {
//间接执行并将null作为函数的this,并将参数传过来
plugin.apply(null, args)
}
installedPlugins.push(plugin)
return this
}
}
发表回复