![](/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.