Reputation: 82
I can't get a vuex getter to update, when a state object changes. I'm trying to get a vuex getter to return a total sum of the values in a state object, with a reduce function.
// 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)
After setting a shipping fee key-value pair in the state.shippingFees object, the getter still just returns 0.
Upvotes: 5
Views: 11680
Reputation: 9009
Refer to the official documentation Caveats in Vue. You can't change the array elements by index. There is to ways to achieve the same with reactivity as given below
state.shippingFees.splice(index, 1, val)
//using the splice method, replace the element at index
or. alternatively, you can use
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 can not detect the change when you directly update the item using the index, or modify the array length property.
Upvotes: 2
Reputation: 2244
Vue does not allow dynamically adding new root-level reactive properties to an already created instance. However, it’s possible to add reactive properties to a nested object using the Vue.set(object, key, value) method
Hence the way you are updating above object it is not reactive. Hence your values are not updated in the getter. To know more about vue reactivity read here.
For making it reactive you need to use $set or object.assign
Update your mutation as below =>
Vue.$set(state.shippingFees,method.sellerId,method.fee);
Upvotes: 6