Mutations
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:

你不能直接调用一个 mutation handler。这个选项更像是事件注册:“当触发一个类型为 increment 的 mutation 时,调用此函数。”要唤醒一个 mutation handler,你需要以相应的 type 调用 store.commit 方法:

提交载荷(Payload)
你可以向 store.commit 传入额外的参数,即 mutation 的 载荷(payload):

在模板里修改按钮的 store.commit( ) 方法 传递的参数,我们传递10,意思就是每次加10。

在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读:


对象风格的提交方式
提交 mutation 的另一种方式是直接使用包含 type 属性的对象:

当使用对象风格的提交方式,整个对象都作为载荷传给 mutation 函数,因此 handler 保持不变.

在组件中提交 Mutation( mapMutations 辅助函数 )
可以在组件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)。

网友评论