Vuex 深度状态突变最佳实践
Vuex deep state mutations best practice
是否建议在突变处理程序中执行状态突变,即使您没有通过 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
参数找到要变异的对象
在第二次提交中,要变异的对象在提交之前找到并与有效负载一起传入。这种方式使变异处理程序更通用,它不必知道如何找到要变异的对象。然而,它看起来 "weird" 因为我见过的几乎所有变异示例都访问了 state
参数。
我问这个是因为我发现自己不经意地改变了存储中嵌套对象的属性,并且想知道我是否应该在存储中执行所有的改变。我说的是死的简单突变,比如翻转布尔属性。这样做真的值得编写突变样板吗?
Is it really worth writing the mutation boilerplate to do that?
是的,因为您能够跟踪实际发生的事情。可以手动或通过 vue-devtool
等工具跟踪突变。它还迫使您不能简单地从任何地方编辑您的商店,而是始终通过允许您以通用方式输入数据的变更。因此,您还能够以相同的方式对所有传入数据执行操作。
这是您不应该做的事情,因为您可以通过 state.foo[0]
简单地访问突变中的状态。您可以简单地提交 name
.
this.$store.commit('changeName2', {
item: this.$store.state.foo[0],
name: 'foobar'
})
是否建议在突变处理程序中执行状态突变,即使您没有通过 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
参数找到要变异的对象
在第二次提交中,要变异的对象在提交之前找到并与有效负载一起传入。这种方式使变异处理程序更通用,它不必知道如何找到要变异的对象。然而,它看起来 "weird" 因为我见过的几乎所有变异示例都访问了 state
参数。
我问这个是因为我发现自己不经意地改变了存储中嵌套对象的属性,并且想知道我是否应该在存储中执行所有的改变。我说的是死的简单突变,比如翻转布尔属性。这样做真的值得编写突变样板吗?
Is it really worth writing the mutation boilerplate to do that?
是的,因为您能够跟踪实际发生的事情。可以手动或通过 vue-devtool
等工具跟踪突变。它还迫使您不能简单地从任何地方编辑您的商店,而是始终通过允许您以通用方式输入数据的变更。因此,您还能够以相同的方式对所有传入数据执行操作。
这是您不应该做的事情,因为您可以通过 state.foo[0]
简单地访问突变中的状态。您可以简单地提交 name
.
this.$store.commit('changeName2', {
item: this.$store.state.foo[0],
name: 'foobar'
})