![](/img/trans.png)
[英]VueJs/ChartJs - single file component computed property only renders when I click the component in Vue Dev Tools
[英]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.