Vuex getter不会根据状态更改进行更新

时间:2019-03-15 10:28:27

标签: javascript vue.js vuejs2 vuex

当状态对象更改时,我无法更新vuex getter。 我正在尝试使用vuex吸气剂,以带有reduce函数的状态对象返回值的总和。

// Mutation
state.shippingFees[method.sellerId] = method.fee; // state.shippingFees = { 1: 1900 }; etc.

// Getter
totalShippingFees: state => Object.values(state.shippingFees).reduce((total, fee) => total + fee, 0)

在state.shippingFees对象中设置运费键-值对之后,getter仍然只返回0。

3 个答案:

答案 0 :(得分:2)

Vue无法检测到属性的添加或删除

使用Vue.set(state.shippingFees, method.sellerId, method.fee)

更多详细信息here

答案 1 :(得分:2)

请参考Vue中的官方文档Caveats。您不能按索引更改数组元素。有如下方法可以实现相同的反应性

state.shippingFees.splice(index, 1, val) 
//using the splice method, replace the element at index

或。或者,您可以使用

Vue.set(state.shippingFees, index , val)

//You can also use the vm.$set instance method, which is an alias for the global Vue.set method
vm.$set(vm.items, indexOfItem, newValue)

当您使用索引直接更新项目或修改数组长度属性时,Vue无法检测到更改。

答案 2 :(得分:1)

Vue不允许向已创建的实例动态添加新的根级别反应性属性。但是,可以使用Vue.set(object,key,value)方法向嵌套对象添加反应性属性

因此,您在对象上方进行更新的方式不是被动的。因此,您的值不会在getter中更新。要了解有关Vue反应性的更多信息,请阅读here

要使其具有反应性,您需要使用$ set或object.assign

如下更新您的突变=>

Vue.$set(state.shippingFees,method.sellerId,method.fee);