开发中我们常常用Vue.use(Router)、Vue.use(iView)等等,use方法做了什么呢?
我们上源码
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
}
}
plugin
参数为函数或者对象类型,首先Vue会去寻找这个插件在已安装的插件列表里有没有,如果没有,则进行安装插件,如果有则跳出函数,这保证插件只被安装一次。
接着通过toArray
方法将参数变成数组,再判断plugin
的install
属性是否为函数,或者plugin
本身就是函数,最后执行plugin.install
或者plugin
的方法。
在项目中我们可以写一个简单的插件,里面可以包含全局函数,
export default function(Vue) {
Vue.prototype.test = function() {
console.log("test success")
}
}
然后我们在main.js
引入这个文件,如:
Vue.use(globalFunc)
这样我们就可以全局使用this.test()
来访问这个方法了。
不过,我们还是建议将插件写成对象的形式,这样更加容易拓展