-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Mutation #8
Comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
基本用法
每个 mutation 包含一个字符串的事件类型 (type)和一个回调函数(handler)。这个回调函数接受 state 作为第一个参数:
触发mutation,应该像下面这样提交mutation的type
提交载荷(Payload)
我们可以向
stroe.commit
传入额外的参数,即mutation的载荷( payload )大多情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的mutation会更易读:
对象风格的提交方式
提交mutation的另一种方式是直接使用包含type属性的对象:
当使用对象风格的提交方式,整个对象都作为载荷传给 mutation 函数,因此 handler 保持不变:
Mutation 需遵守 Vue 的响应规则
1.最好提前在你的 store 中初始化好所有所需属性。
2.当需要在对象上添加新属性时,应该:
使用
Vue.set(obj, 'newProp', 123)
, 或者以新对象替换老对象。例如,利用对象展开运算符我们可以这样写:
Mutation 必须是同步函数
一条重要的原则就是要记住 mutation 必须是同步函数。为什么?请参考下面的例子:
在组件中提交 Mutation
在组件中可以使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)。例子:
The text was updated successfully, but these errors were encountered: