繁体   English   中英

在我单击 Vue Devtools 中的组件之前,计算值不会显示

[英]Computed value not display until I click component in Vue Devtools

我的计算值有问题。 如果我将商品添加到购物车, totalPrice将保持为 0,直到我在 Vue Devtools 中单击该组件,它才会显示该值。 但是, Item Count工作正常。 为什么会这样? :/

data() {
    return {
      totalPrice: 0,
    };
  },

computed: {
    calcTotal() {
        this.cart.forEach((item) => {
            this.totalPrice += item.price * item.quantity
        });
        return this.totalPrice;
    }
  }

我用它来显示整个购物车的总价。

<div>
  <table class="table">
    <tr v-show="cart.length > 0">
      <td>Item count ({{this.cart.length}})</td>
      <td></td>
      <td><b>Net Payable</b></td>
      <td>{{ totalPrice }}</td>
    </tr>
  </table>
</div>

不要在计算属性中改变你的data属性。 这是结束无限循环的好方法。 它们应该尽可能接近纯函数。

totalPrice应该是您的计算属性,它将cart项目减少为一个数字( price * quantity的总和)

// Adjust locale and currency code accordingly
const currencyFormatter = Intl.NumberFormat("en", { style: 'currency', currency: 'USD' })

export default {
  data: () => ({
    cart: []
  }),
  filters: {
    currency: (value) => currencyFormatter.format(value)
  },
  computed: {
    totalPrice: ({ cart }) =>
      cart.reduce((total, item) => total + item.price * item.quantity, 0)
  }
}
<td>{{ totalPrice | currency }}</td>

另见~过滤器

暂无
暂无

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

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