Vue技术

Vue.use()在new Vue() 之前使用的原因浅析

2021-04-20  本文已影响0人  为光pig

先看Vue.use做了什么

Vue.use = function (plugin: Function | Object) {
  //Vue构造函数上定义_installedPlugins 避免相同的插件注册多次
  const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
  // import是单例模式
  //所以plugin不论是Fuction还是Object同一个插件都是同一个
  if (installedPlugins.indexOf(plugin) > -1) {
   return this
  }

  // additional parameters
  const args = toArray(arguments, 1)
  // Vue作为第一个参数传递给插件
  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 // 返回的是this,可以链式调用
 }
do:
Vue.prototype._init中合并options
Vue.prototype._init = function (options?: Object) {
  const vm: Component = this
  // a uid
  vm._uid = uid++
  let startTag, endTag
  ...
  vm.$options = mergeOptions(
    resolveConstructorOptions(vm.constructor),
    options || {},
    vm
   )
   ...
   // 挂载到dom上
  if (vm.$options.el) {
   vm.$mount(vm.$options.el)
  }
}

new Vue(options)时首先会执行this._init进行初始化,将Vue上的属性和options进行合并,然后在进行事件、生命周期等的初始化。beforeCreate,created生命周期的hook函数也是在这里进行调用

如果Vue.usenew Vue()之后执行,this._init()时你使用的插件的内容还没有添加到Vue.options.components、Vue.options.directives、Vue.options.filters等属性中。所以新初始化的Vue实例中也就没有插件内容

上一篇 下一篇

猜你喜欢

热点阅读