initUse的源码:vue
// Vue源码文件路径:src/core/global-api/use.js
import { toArray } from '../util/index'
export function initUse (Vue: GlobalAPI) {
Vue.use = function (plugin: Function | Object) {
const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
// additional parameters
const 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)
}
installedPlugins.push(plugin)
return this
}
}
复制代码
源码中vue的插件不容许重复注册。 而且接收的plugin参数的限制是Function | Object两种类型。 对于这两种类型有不一样的处理。 首先将咱们传入的参数整理成数组 => const args = toArray(arguments, 1)。api
// Vue源码文件路径:src/core/shared/util.js
export function toArray (list: any, start?: number): Array<any> {
start = start || 0
let i = list.length - start
const ret: Array<any> = new Array(i)
while (i--) {
ret[i] = list[i + start]
}
return ret
}
复制代码
对象中包含install方法,那么咱们就调用这个plugin的install方法并将整理好的数组当成参数传入install方法中。 => plugin.install.apply(plugin, args) 若是咱们传入的plugin就是一个函数,那么咱们就直接调用这个函数并将整理好的数组当成参数传入。 => plugin.apply(null, args) 以后给这个插件添加至已经添加过的插件数组中,标示已经注册过 => installedPlugins.push(plugin) 最后返回Vue对象。数组