当状态对象更改时,我无法更新 vuex getter。
我试图让一个 vuex getter 返回状态对象中值的总和,并带有一个 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。

最佳答案

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

因此,您更新上述对象的方式不是 react 性的。因此,您的值不会在 getter 中更新。要了解有关 vue react 性的更多信息,请阅读 here

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

如下更新您的突变 =>

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

10-06 02:31