【发布时间】:2018-10-03 03:44:24
【问题描述】:
是否建议在突变处理程序中执行状态突变,即使您没有通过state 参数访问状态?
让我举个例子。
const store = new Vuex.Store({
state: {
foo: [{ name: 'bar' }]
},
mutations: {
changeName1 (state, payload) {
state.foo[0].name = payload.name
},
changeName2 (state, payload) {
let { item, name } = payload
item.name = name
}
}
})
// Inside a component
this.$store.commit('changeName1', { name: 'foobar' })
// Inside a component
this.$store.commit('changeName2', {
item: this.$store.state.foo[0],
name: 'foobar'
})
在第一次提交中,您通过state 参数找到要变异的对象。
在第二次提交中,在提交之前找到要变异的对象,并与有效负载一起传入。这种方式使突变处理程序更加通用,它不必知道如何找到要突变的对象。但是,它看起来很“奇怪”,因为我见过的几乎所有突变示例都访问了state 参数。
我问这个是因为我发现自己随意地改变了存在于 store 中的嵌套对象的属性,并且想知道我是否应该在 store 内执行所有的突变。我说的是简单的突变,比如翻转布尔属性。真的值得编写突变样板来做到这一点吗?
【问题讨论】:
-
看起来您的代码会有反应性问题。即使您可以在存储之外改变深层对象,它也不会是被动的。应该使用Vue.set