[英]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.