【Vue】Vue.use(plugin)

开发中我们常常用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方法将参数变成数组,再判断plugininstall属性是否为函数,或者plugin本身就是函数,最后执行plugin.install或者plugin的方法。

在项目中我们可以写一个简单的插件,里面可以包含全局函数,

export default function(Vue) {
	Vue.prototype.test = function() {
		console.log("test success")
	}
}

然后我们在main.js引入这个文件,如:
Vue.use(globalFunc)
这样我们就可以全局使用this.test()来访问这个方法了。
不过,我们还是建议将插件写成对象的形式,这样更加容易拓展

猜你喜欢

转载自blog.csdn.net/jzq950522/article/details/88399054
今日推荐