Skip to content

Vuex 的 install 流程

当我们使用 Vuex 的时候,都会在项目的main.js文件中去通过Vue.use(Vuex)去加载 Vuex 插件。

那么这一步的主要作用是什么?

通过 Vue.mixin 功能在每一个组件的 beforeCreate 阶段提供一个获取根 store 的能力(this.$store)。其逻辑很简单也就是通过 组件的 parent 去不断向上寻找 store 的过程

源码

js
export default function (Vue) {
  // 获取当前Vue 的主要版本 2.x 还是 1.x
  const version = Number(Vue.version.split(".")[0])

  if (version >= 2) {
    // 2.x 版本 使用
    Vue.mixin({ beforeCreate: vuexInit })
  } else {
    // override init and inject vuex init procedure
    // for 1.x backwards compatibility.
    const _init = Vue.prototype._init
    Vue.prototype._init = function (options = {}) {
      options.init = options.init ? [vuexInit].concat(options.init) : vuexInit
      _init.call(this, options)
    }
  }

  /**
   * Vuex init hook, injected into each instances init hooks list.
   */
  /*
      在每一个Vue组件创建之前执行,是的组件实例对象中存在 $store 属性。
      this.$store.xxxx
     */
  function vuexInit() {
    // 获取options
    const options = this.$options
    // store injection
    // 让每一个组件都有一个 $store 属性
    /*
      Vue的组件是自上而下执行的,所以我们在new Vue({ store }) ,这时候就是判断 if(options.store)的时候,
      对于子组件 判断options.parent && options.parent.$store 然后将父组$store赋给子组件,
      因为是自上而下一层一层执行,所以对于每一个子组件其父组件肯定存在 $store

    */
    if (options.store) {
      this.$store = typeof options.store === "function" ? options.store() : options.store
    } else if (options.parent && options.parent.$store) {
      this.$store = options.parent.$store
    }
  }
}

可以粗略的统计其主要作用分为以下几个:

  • Vue.mixin 定义全局混合方法,使得每一个组件都能获取到 this.$store

  • 区分 Vue 1 和 2 不同的处理方法