![](/img/trans.png)
[英]How to pass data from vuex store through module to vue component?
[英]How to get total to display on vue component from vuex store?
我創建了一個購物車系統,我的 home 組件可以將元素添加到我的購物車組件中,所有這些都保存在我的商店中。 我想計算購物車中所有產品的總數,在我的 vuex 商店中,並在購物車組件中顯示價值。 當我嘗試這樣做時,我得到了 NaN。 我的代碼如下。 我將如何解決這個問題?
這是在我的購物車組件中,其中購物車數據是所有購物車組件都存儲在 vuex 存儲中的數組
total: function(){
let tot = 0;
this.$store.state.cartdata.forEach(product => tot +=
this.$store.state.products.price);
return tot;
}
這就是我在 vue 組件中呈現總數的方式。
Checkout ( Total: {{total}} )
我相信最好的辦法是使用計算屬性來計算總數,這樣組件就不會重新計算總數太多次,或者可以使用相同的邏輯創建Vuex getter 。
computed: {
total () {
this.$store.state.cartdata.reduce((result, product) => {
// We need to ensure that the property is of the type Number.
result += Number(product.price);
return result;
}, 0);
},
},
請注意,屬性product.price
可能是錯誤的,因為未提供數據結構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.