【发布时间】:2018-03-22 03:25:09
【问题描述】:
我正在学习 Vuex,但在构建我的应用程序时遇到了问题。
考虑这些代码,它们都在做同样的事情:
示例 #1:
mutations: {
add: function(state, employee) {
state.employees.push(employee);
},
remove: function(state, index) {
state.employees.splice(index, 1);
}
},
actions: {
generate: function(context) {
context.commit('add', 'John Smith');
}
}
如果动作应该是异步的,那么这是错误的。
示例 #2:
mutations: {
add: function(state, employee) {
state.employees.push(employee);
},
remove: function(state, index) {
state.employees.splice(index, 1);
},
generate: function(state) {
this.commit('add', 'John Smith');
}
}
我可以从另一个突变中调用一个突变吗?如果不是,那就大错特错了。
示例 #3:
mutations: {
add: function(state, employee) {
state.employees.push(employee);
},
remove: function(state, index) {
state.employees.splice(index, 1);
},
generate: function(state) {
state.employees.push('John Smith');
}
}
另一方面,这重复了逻辑 - 这似乎是错误的!
示例 #4:
商店
mutations: {
add: function(state, employee) {
state.employees.push(employee);
},
remove: function(state, index) {
state.employees.splice(index, 1);
}
}
组件
methods: {
addJohnSmith: function() {
this.$store.commit('add', 'John Smith')
},
}
这个看起来不错,但是我认为这是正确的方法只有当所有输入都来自组件时。如果我需要此功能由 store 控制,例如,如果我需要以某种方式转换此值,该怎么办?该组件应该足够愚蠢以至于不关心这一点。一个人为的示例可能是在员工姓名之前添加一个随机生成的头衔,因此最终结果如下所示:John Smith 先生。
哪一种是处理这个问题的正确方法?
【问题讨论】: