vue commit 方法实现
Vue 中 Commit 方法的实现
在 Vue 中,commit 方法是 Vuex 的核心功能之一,用于提交 mutation 来修改状态。以下是实现 commit 方法的关键步骤和代码示例。
基本实现原理
Vuex 的 commit 方法通过调用 mutations 来同步更新 state。每个 mutation 都有一个字符串类型的事件类型(type)和一个回调函数(handler)。
class Store {
constructor(options) {
this._mutations = options.mutations || {}
this._actions = options.actions || {}
this._wrappedGetters = options.getters || {}
}
commit(type, payload) {
const entry = this._mutations[type]
if (!entry) {
console.error(`[vuex] unknown mutation type: ${type}`)
return
}
entry(this.state, payload)
}
}
使用示例
在 Vuex 中定义 mutations 并通过 commit 调用:
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state, payload) {
state.count += payload.amount
}
}
})
// 调用 commit
store.commit('increment', { amount: 10 })
支持对象风格的提交
commit 方法还支持对象风格的提交方式,允许包含 type 属性:
commit(type, payload) {
if (typeof type === 'object') {
payload = type
type = type.type
}
const entry = this._mutations[type]
if (!entry) {
console.error(`[vuex] unknown mutation type: ${type}`)
return
}
entry(this.state, payload)
}
// 对象风格调用
store.commit({
type: 'increment',
amount: 10
})
结合 Vue 的响应式系统
为了确保 state 的修改能够触发视图更新,Vuex 内部会使用 Vue 的响应式系统:

class Store {
constructor(options) {
this._vm = new Vue({
data: {
$$state: options.state
}
})
}
get state() {
return this._vm._data.$$state
}
commit(type, payload) {
const entry = this._mutations[type]
entry(this.state, payload)
}
}
注意事项
- mutations 必须是同步函数,异步逻辑应放在 actions 中。
- 使用常量作为 mutation 类型可以提高代码可维护性。
- 在组件中可以通过
this.$store.commit调用 commit 方法。






