vue commit 方法实现
Vue 中 Commit 方法的实现
在 Vue 中,commit 方法是 Vuex 的核心功能之一,用于提交 mutation 来修改状态。以下是实现 commit 方法的关键步骤:
初始化 Store 时定义 commit 方法
在 Vuex 的 Store 构造函数中,会初始化 commit 方法。该方法接收两个参数:type(mutation 类型)和 payload(载荷数据)。
class Store {
constructor(options) {
this._mutations = options.mutations || {}
this.commit = this.commit.bind(this)
}
commit(type, payload) {
const entry = this._mutations[type]
if (!entry) {
console.error(`[vuex] unknown mutation type: ${type}`)
return
}
entry(this.state, payload)
}
}
绑定上下文
为确保 commit 方法中的 this 指向 Store 实例,需要在构造函数中通过 bind 方法绑定上下文。
执行 Mutation
commit 方法通过 type 找到对应的 mutation 函数,并将当前状态和 payload 作为参数传入执行。Mutation 必须是同步函数,直接修改状态。

示例用法
在组件中通过 this.$store.commit 调用:
this.$store.commit('increment', 10)
对应的 mutation 定义:

const store = new Vuex.Store({
state: { count: 0 },
mutations: {
increment(state, payload) {
state.count += payload
}
}
})
实现响应式状态更新
Vuex 利用 Vue 的响应式系统,在初始化 Store 时将 state 转为响应式数据:
class Store {
constructor(options) {
this._vm = new Vue({
data: {
$$state: options.state
}
})
}
get state() {
return this._vm._data.$$state
}
}
通过 Vue 实例的 data 选项包裹 state,使状态变更能触发视图更新。
严格模式下的实现
在严格模式下,Vuex 会检测是否通过 mutation 修改状态:
class Store {
constructor(options) {
this.strict = options.strict || false
if (this.strict) {
this._vm.$watch(
() => this.state,
() => {
console.assert(
this._committing,
'Do not mutate vuex store state outside mutation handlers.'
)
},
{ deep: true, sync: true }
)
}
}
commit(type, payload) {
this._committing = true
const entry = this._mutations[type]
entry(this.state, payload)
this._committing = false
}
}
通过 _committing 标志位确保状态修改只在 mutation 中发生。






