Skip to content

install

javascript
function install (_Vue) {

  // 判断是否已经安装
  if (Vue && _Vue === Vue) {
    return
  }

  // 记录最新的 Vue
  Vue = _Vue

  // 开始安装
  applyMixin(Vue)
}

function applyMixin (Vue) {
  // 获取 Vue 版本
  const version = Number(Vue.version.split('.')[0])

  if (version >= 2) {
    // 2.0 及以上版本,通过 Mixin 向每个组件中注入 beforeCreate 钩子
    Vue.mixin({ beforeCreate: vuexInit })
  } else {
    // ...
  }

  function vuexInit () {

    // 获取 $options
    const options = this.$options

    // store injection
    if (options.store) {

      // 由于我们只会在 main.js 中 new Vue() 时往配置项中传入 store
      // 如果 this.$options.store 有值说明是根组件,直接将 store 挂在到根组件上
      this.$store = typeof options.store === 'function'
        ? options.store()
        : options.store
    } else if (options.parent && options.parent.$store) {

      // 否则不是根组件,那么就看有没有父组件并且父组件上有没有挂载 store
      // 如果都有,该组件自身上也挂载父组件上的 store,这样就能让所有组件都访问到同
      // 一个 store。
      this.$store = options.parent.$store
    }
  }
}