概念
插件的作用:插件通常用来为Vue添加全局功能,插件的功能没有严格的限制,一般有以下几种:
- 添加
全局方法
或property
,如:vue-custom-element
- 添加全局资源:
指令、过滤器、过度等
,如:vue-touch
- 通过全局混入来添加一些组件选项,如: vue-router
- 添加Vue实例方法,通过把它们添加到
Vue.prototype
上实现
- 一个库,提供自己的API,同时提供上边的一种或几种功能,如: vue-router
通过全局方法 Vue.use()使用插件,它需要你在调用new Vue()启用应用之前完成。
Vue.use(myPlugin)
new Vue({
})
所以,Vue.use的参数必须是一个Object对象
或者function函数
,如果是对象的话,必须要提供install
方法,之后会将Vue作为参数传入
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
}
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
}
}
// toArray 方法源码
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
}
总结
- 首先判断插件 plugin 是否是对象或者函数 代码:
`plugin: Function | Object`
- 判断Vue是否已注册过这个插件,如果注册过就跳出方法,代码:
const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
- 处理Vue.use的入参,将第一个参数之后的参数归集,并在首部塞入this上下文,代码:
const args = toArray(arguments, 1)
args.unshift(this)
- 断插件是否有install方法,如果有就执行install()方法。没有就直接把plugin当Install执行。代码:
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args)
} else if (typeof plugin === 'function') {
plugin.apply(null, args)
}
- 缓存插件:
installedPlugins.push(plugin)