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

另请参阅~过滤器

最新更新