? options.store()
: options.store
} else if (options.parent && options.parent.$store) {
/* 子组件直接从父组件中获取 $store,这样就保证了所有组件都公用了全局的同一份 store*/
this.$store = options.parent.$store
}
}
根节点存在 stroe 时,则直接将
options.store 赋值给
this.$store 。否则则说明不是根节点,从父节点的
$store 中获取。通过这步的操作,我们就以在任意一个 vm 中通过 this.$store 来访问 Store 的实例。接下来我们反过来说说 Vue.mixin()。
Vue.mixin()
全局注册一个混入,影响注册之后所有创建的每个 Vue 实例。插件作者可以使用混入,向组件注入自定义的行为。 不推荐在应用代码中使用。
在 vue 的
initGlobalAPI 入口方法中调用了
initMixin$1(Vue) 方法:
function initMixin$1 (Vue) {
Vue.mixin = function (mixin) {
this.options = mergeOptions(this.options, mixin);
return this
};
}Vuex 注入 Vue 生命周期的过程大概就是这样,如果你感兴趣的话,你可以直接看看 Vuex 的源码,接下来我们说说 Store。
Store
上面我们讲到了
vuexInit 会从 options 中获取 Store。所以接下来会讲到 Store 是怎么来的呢?我们使用 Vuex 的时候都会定义一个和下面类似的 Store 实例。
import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'Vue.use(Vuex)
const state = {
showState: 0,
}
export default new Vuex.Store({
strict: true,
state,
getters,
})
不要在发布环境下启用严格模式。严格模式会深度监测状态树来检测不合规的状态变更 —— 请确保在发布环境下关闭严格模式,以避免性能损失。
state 的响应式
你是否关心 state 是如何能够响应式呢?这个主要是通过 Store 的构造函数中调用的
resetStoreVM(this, state) 方法来实现的。这个方法主要是重置一个私有的 _vm(一个 Vue 的实例) 对象。这个 _vm 对象会保留我们的 state 树,以及用计算属性的方式存储了 store 的 getters。现在具体看看它的实现过程。
/* 使用 Vue 内部的响应式注册 state */
function resetStoreVM (store, state, hot) {
/* 存放之前的vm对象 */
const oldVm = store._vm store.getters = {}










