简体   繁体   English

如何从 vuex 商店获取总计以显示在 vue 组件上?

[英]How to get total to display on vue component from vuex store?

I creating a cart system whereby my home component can add elements to my cart component and all this is persisted in my store.我创建了一个购物车系统,我的 home 组件可以将元素添加到我的购物车组件中,所有这些都保存在我的商店中。 I would like to calculate the total of all products in cart, in my vuex store and present the value in the cart component.我想计算购物车中所有产品的总数,在我的 vuex 商店中,并在购物车组件中显示价值。 When i try doing this i get NaN.当我尝试这样做时,我得到了 NaN。 My code is below.我的代码如下。 How would i go about solving this?我将如何解决这个问题?

this is within my cart component whereby cartdata is the array in which all the cart components are stored within the vuex store这是在我的购物车组件中,其中购物车数据是所有购物车组件都存储在 vuex 存储中的数组

total: function(){
        let tot = 0;
        this.$store.state.cartdata.forEach(product => tot += 
        this.$store.state.products.price);
        return tot;
      }

This is how i present the total in the vue component.这就是我在 vue 组件中呈现总数的方式。

Checkout ( Total: {{total}} )

I believe that the best would be to calculate the total either with a computed property , so the component won't recalculate the total too many times, or a Vuex getter could be created using the same logic.我相信最好的办法是使用计算属性来计算总数,这样组件就不会重新计算总数太多次,或者可以使用相同的逻辑创建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);
  },
},

Please note that the property product.price might be wrong, as the data structure wasn't provided.请注意,属性product.price可能是错误的,因为未提供数据结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM