简体   繁体   English

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

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

I have problems with my computed value.我的计算值有问题。 If I add item to cart, the totalPrice will remain 0, until I click the component in Vue Devtools, it will display the value.如果我将商品添加到购物车, totalPrice将保持为 0,直到我在 Vue Devtools 中单击该组件,它才会显示该值。 However, the Item Count working normally.但是, Item Count工作正常。 Why is that happening?为什么会这样? :/ :/

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

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

I am using it to display the total price for whole cart.我用它来显示整个购物车的总价。

<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>

Do not mutate your data properties inside a computed property.不要在计算属性中改变你的data属性。 It's a great way to end up in an infinite loop.这是结束无限循环的好方法。 They should be as close to pure functions as possible.它们应该尽可能接近纯函数。

totalPrice should be your computed property that reduces the cart items to a number (the sum of price * quantity ) 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>

See also ~ Filters另见~过滤器

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

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