function totalQuantity() {
let total = 0
for(let k in cart)
total += cart[k].quantity;
return total;
}
You can add function as a computed property and then use it as
{{ totalQuantity }}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have a controller that is passing an instance of cart to my .vue page.
I can output {{cart}} on the .vue file, which gives the following paired array, where the key value is the id of the product
{ "1": { "title": "Chaos Space Marines Codex", "quantity": 3, "price": "29.99" }, "2": { "title": "Chaos Space Marines Datacards", "quantity": 2, "price": "19.99" }, "3": { "title": "Chaos Space Marines Warp-smith", "quantity": 1, "price": "20.99" } }
I am trying to get both the count (number of individual products in the cart) and a total value for the quantities and price of what is in the cart.
Using {{cart.length}} is simply displaying nothing at all... please help!
@aluckman321 Space Marines? Is this Warhammer 40K? That certainly takes me back 15 years or so 😅
I’m not sure where you’re storing this cart variable, whether it’s a prop or a data member. But to answer your questions, you can use computed properties to calculate both the item count, and the item subtotal from your cart array:
computed: {
itemCount() {
return this.items.reduce(function (carry, item) => {
return carry + item.quantity;
}, 0);
},
itemTotal() {
return this.items.reduce(function (carry, item) => {
return carry + (item.quantity * price);
}, 0);
},
}
So assuming this.cart is an array in either your props or data, the reduce method will run a function over each item in the array, and add to a carry value, eventually ending up with either the total number of items in the itemCount computed property, or the item total in the itemTotal computed property. You’d call these computed properties just like any other property in your template:
<p>You have {{ itemCount }} item(s) in your cart.</p>
<p>Cart total: {{ itemTotal }} GBP</p>
If you’re using the Composition API in Vue 3, then those computed properties would look like this instead:
const itemCount = computed(() => items.reduce(function (carry, item) => {
return carry + item.quantity;
}, 0));
const itemTotal = computed(() => items.reduce(function (carry, item) => {
return carry + (item.quantity * item.price);
}, 0));
Please or to participate in this conversation.