const store = new Vue.Store({
state: {
count: 1
},
mutations: {
inctement (state) {
state.count++
}
}
})当触发一个类型为 increment 的 mutation 时,调用此函数。”要唤醒一个
mutation handler,你需要以相应的 type 调用 store.commit 方法
store.commit('increment')提交载荷(Payload)
你可以向store.commit 传入额外的参数,即mutation 的载荷:
mutations: {
increment (state, n) {
state.count += n
}
}
store.commit('increment', 10)在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录 mutation会更易读。
mutations: {
increment (state,payload) {
state.count += payload.amount
}
}
store.commit('increment', {
amount:10
})对象风格的提交方式
提交mutation 的另一种方式直接使用包含 type 属性的对象:
store.commit({
type: 'increment',
amount:10
})当使用对象风格的提交方式,整个对象作为载荷传给mutation 函数,因此handler保持不变:
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}Mutations 需遵守vue 的响应规则
既然Vuex的store 中的状态是响应式的,那么当我们变更状态时,监视状态的vue更新 ,这也意味值Vue 中的mutation 也需要与使用 Vue 一样遵守一些注意事项。
1. 最好提前在你的store 中初始化好所有的所需要的属性。
2.当需要在对象上提交新属性时,你应该使用
Vue.set(obj, 'newProp', 123)使用新对象代替老对象 state.obj= {…state.obj ,newProp: 123}










