Vuex源码解析(一) 对于 install 和 applyMixin 解析

126 阅读1分钟

以 Vuex3.6.2 为例

Vuex3.6.2 中 install

  • @param {Vue} _Vue vue 实例
  • 防止重复安装
  • 通过 mixin 在 Vue beforeCreate 创建时初始化 vuex applyMixin方法

install方法

export function install (_Vue) {
  // install 方法默认有个参数是 Vue 实例 是 Vue.use 实现的
  if (Vue && _Vue === Vue) {
    return
  }
  Vue = _Vue
  applyMixin(Vue)
}

applyMixin方法

  • 兼容旧版本
  • Vuex 初始化
// 一整个都是 applyMixin
export default function (Vue) {
  const version = Number(Vue.version.split('.')[0])

  if (version >= 2) {
    // 在 beforeCreate 生命周期混入 vuexInit 方法
    Vue.mixin({ beforeCreate: vuexInit })
  } else {
    // 挂载 _init 兼容Vue 1.x
    const _init = Vue.prototype._init
    Vue.prototype._init = function (options = {}) {
      options.init = options.init
        ? [vuexInit].concat(options.init)
        : vuexInit
      _init.call(this, options)
    }
  }

  // vuex 初始化
  function vuexInit() {
    // 拿到 option   this是Vue
    const options = this.$options
    // store injection
    // 检查 有没有 store 挂载
    if (options.store) {
      // 有挂载执行这个
      this.$store = typeof options.store === 'function'
        ? options.store()
        : options.store
    } else if (options.parent && options.parent.$store) {
      // 子组件,有父组件,且父组件上有 $store 属性
      this.$store = options.parent.$store
    }
  }
}