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