VUE使用use原理

290 阅读1分钟

什么是VUE.use

记录一个vue原理问题

Vue中使用的第三方库在引入后,像Store,插件,router等,都需要使用use引入到实例中。 通过全局方法Vue.use使用插件,会自动阻止多次注册相同插件,传入一个参数,该参数类型必须是Object或Function,如果是Object,对象内部需要有一个key为install的function,如果是Function,那么这个函数就被当做install。 在Vue.use执行时,install会默认执行,当install执行时第一个参数就是Vue,其他参数是Vue.use执行时传入的其他参数。

install: (app: any, params: any) => {
        app.config.globalProperties.$translate = (key: string) => {
            return '翻译文字'
        }
    }
    

像上面这个使用文字中英文翻译的方法,在内部使用app实例,给他添加全局方法,

VUE.use源码

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
 }
}

源码中首先限制传入的类型,然后判断该插件是不是注册过,然后调用该插件install方法。

VUE.use使用时机

在使用vuex,router等全局功能时候使用,全局数据,防止冲突。