一、源码分析
首先我们来看一下Vue.use的源码,代码很简单,就几行,如下:
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
}
- 从源码中可以看到首先会判断当前插件是否已经存在在,如果已存在插件列表(_installedPlugins),则返回;对接收的plugin类型有限制,必须是Function | Object
- 如果传入的 plugin类型是Object,则会判断 plugin.install是否是Function,则会将出plugin参数以外的其他参数传入并执行;如果plugin就是Function, 同样会传入其余参数并执行
- 最后将插件 插入_installedPlugins列表
二、Vue.use使用—开发vue插件
插件通常会为 Vue 添加全局功能。插件的范围没有限制,一般有下面几种:
- 添加全局方法或者属性
- 添加全局资源:指令/过滤器/过渡等
- 通过全局 mixin 方法添加一些组件选项
- 添加 Vue 实例方法,通过把它们添加到 Vue.prototype 上实现
- 一个库,提供自己的 API,同时提供上面提到的一个或多个功能,如 vue-router
示例如下:
Vue.use({
install: Function (Vue, options) {
// 1. 添加全局方法或属性
Vue.myGlobalMethod = function () {
// 逻辑...
}
// 2. 添加全局资源
Vue.directive('my-directive', {
bind(el, binding, vnode, oldVnode) {
// 逻辑...
}
update(el: any, { value, oldValue }: VNodeDirective, vnode: VNodeWithData ){
// 逻辑...
}
})
// 3. 注入组件, 代码复用
Vue.mixin({
created: function () {
// 逻辑...
}
...
})
// 4. 添加实例方法
Vue.prototype.$myMethod = function (methodOptions) {
// 逻辑...
}
})