簡體   English   中英

Vuex getter 不更新狀態變化

[英]Vuex getter not updating on state changes

當狀態對象發生變化時,我無法更新 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(state.shippingFees, method.sellerId, method.fee)

更多細節在這里

Vue 不允許動態地將新的根級響應屬性添加到已創建的實例中。 但是,可以使用 Vue.set(object, key, value) 方法向嵌套對象添加反應屬性

因此,您更新上述對象的方式不是反應性的。 因此,您的值不會在 getter 中更新。 要了解有關 vue 反應性的更多信息,請閱讀此處

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

如下更新您的突變 =>

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

參考官方文檔Caveats in Vue。 您不能按索引更改數組元素。 有一些方法可以通過下面給出的反應性來實現相同的目標

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 無法檢測到更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM