在一个购物车列表中,购物车数据来自于 store, 我通过 vm.$set() 给数组每一项添加一个新的属性 isChecked 来关联每一项的选中状态。
computed: {
cartBooks: function() {
var carts = this.$store.getters.getCartBookList;
if (carts.length > 0) {
carts.forEach((item, index, array) => {
this.$set(item, 'isChecked', true);
});
} else {
this.isCheckedAll = false;
}
return carts;
}
}
但是却报错:
"Error: [vuex] Do not mutate vuex store state outside mutation handlers."
请问是否因为 store 中的数据只能通过 mutations 方法来修改,但我在 mutation 之外又通过 vm.$set() 来修改了 store 中的数据才出现这种错误呢?
这种错误要如何处理呢?
1.更准确地说,mutations相当一个事件,只能通过commit来触发,之后才会改变state的状态。
这是修改store中数据的唯一途径。
2.找到getCartBookList对应的type,通过
this.$store.commit('TYPE', xxx);
来提交mutation,以达到修改state的目的。另外,需要注意的是mutation必须是
同步
的。