const wrappedGetters = store._wrappedGetters
const computed = {}
/* 通过 Object.defineProperty 方法为 store.getters 定义了 get 方法。当在组件中调用 this.$store.getters.xxx 这个方法的时候,会访问 store._vm[xxx]*/
forEachValue(wrappedGetters, (fn, key) => {
computed[key] = partial(fn, store)
Object.defineProperty(store.getters, key, {
get: () => store._vm[key],
enumerable: true // for local getters
})
})
const silent = Vue.config.silent
/* 设置 silent 为 true 的目的是为了取消 _vm 的所有日志和警告 */
Vue.config.silent = true
/* 这里new了一个Vue对象,运用Vue内部的响应式实现注册state以及computed*/
store._vm = new Vue({
data: {
$$state: state
},
computed
})
Vue.config.silent = silent
/* 使能严格模式,Vuex 中对 state 的修改只能在 mutation 的回调函数里 */
if (store.strict) {
enableStrictMode(store)
}
if (oldVm) {
/* 解除旧 vm 的 state 的引用,并销毁这个旧的 _vm 对象 */
if (hot) {
store._withCommit(() => {
oldVm._data.$$state = null
})
}
Vue.nextTick(() => oldVm.$destroy())
}
}
state 的响应式大概就是这样实现的,也就是初始化 resetStoreVM 方法的过程。
看看 Store 的 commit 方法
我们知道 commit 方法是用来触发 mutation 的。
commit (_type, _payload, _options) {
/* unifyObjectStyle 方法校参 */
const {
type,
payload,
options
} = unifyObjectStyle(_type, _payload, _options) const mutation = { type, payload }
/* 找到相应的 mutation 方法 */
const entry = this._mutations[type] if (!entry) {
if (process.env.NODE_ENV !== 'production') {
console.error(`[vuex] unknown mutation type: ${type}`)
}
return
}
/* 执行 mutation 中的方法 */
this._withCommit(() => {
entry.forEach(function commitIterator (handler) {
handler(payload)
})
})
/* 通知所有订阅者,传入当前的 mutation 对象和当前的 state */
this._subscribers.forEach(sub => sub(mutation, this.state))
if (
process.env.NODE_ENV !== 'production' &&
options && options.silent
) {
console.warn(
`[vuex] mutation type: ${type}. Silent option has been removed. ` +
'Use the filter functionality in the vue-devtools'
)
}
}
该方法先进行参数风格校验,然后利用
_withCommit 方法执行本次批量触发
mutation 处理函数。执行完成后,通知所有
_subscribers (订阅函数)本次操作的
mutation










