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. However, the Item Count
working normally. 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. 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
)
// 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.