【发布时间】:2021-09-11 04:41:54
【问题描述】:
我是来react/redux 到vue 的,在学习vuex 的过程中,我发现我可以直接改变状态,并且状态变化仍然会反映在使用它的其他组件上。
Redux 禁止这种行为,如果我直接改变状态,其他组件将不会收到有关这些更改的通知,因此我们必须为此使用操作和减速器。
所有这些方法基本上都提供相同的结果。
methods: {
IncrementDirect () {
// mutates the state directly
this.$store.state.counter += 2;
},
incrementDispatch() {
// mutates the state inside actions
this.$store.dispatch("handleIncrement", 2);
},
incrementCommit() {
// mutates the state inside mutations
this.$store.commit("increment", 2);
},
},
我的问题是为什么允许这种行为,以及如果我们可以在应用程序中的任何位置改变状态,为什么我们必须使用 mutations。
【问题讨论】:
-
设置你的存储使用strict mode(用于非生产版本)。至于“为什么”,你大概应该问问原开发者