【问题标题】:How to get total to display on vue component from vuex store?如何从 vuex 商店获取总计以显示在 vue 组件上?
【发布时间】:2019-01-13 12:27:55
【问题描述】:

我创建了一个购物车系统,我的 home 组件可以向我的购物车组件添加元素,所有这些都保存在我的商店中。我想计算购物车中所有产品的总数,在我的 vuex 商店中,并在购物车组件中显示价值。当我尝试这样做时,我得到了 NaN。我的代码如下。我将如何解决这个问题?

这是在我的购物车组件中,其中 cartdata 是所有购物车组件都存储在 vuex 存储中的数组

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

这就是我在 vue 组件中呈现总数的方式。

Checkout ( Total: {{total}} )

【问题讨论】:

  • products 是一个对象,cartdata 是一个对象数组

标签: javascript arrays vue.js store vuex


【解决方案1】:

我相信最好的办法是使用computed property 计算总数,这样组件就不会重新计算总数太多次,或者可以使用相同的逻辑创建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 属性可能有误,因为未提供数据结构。

【讨论】:

    猜你喜欢
    • 2019-11-19
    • 2019-08-18
    • 1970-01-01
    • 2019-03-14
    • 2022-01-11
    • 2021-12-05
    • 2017-12-18
    • 2021-10-20
    • 2022-09-23
    相关资源
    最近更新 更多