0👍
When adding an item to the cart you need some way to specify the quantity to that specific item, the way it was implemented you are adding a quantity but not telling to which item.
To solve that, create an array to be the cart, and add the quantity in the cart associated with the product.
Also, when showing the quantity of each item, you must show it based on the item identity on the cart (in the example below, I’ using the name as identity). That was the issue, you were showing the same value (stock
) to all the items.
Here goes how it must be to work.
<template>
<div>
<h1>Product list</h1>
<div>
<h3>Shopping list:</h3>
<ul>
<li v-for="plant in plantList">
{{ plant.productName }} : {{ cart[plant.productName] }}
<button @click="addPlant(plant)">Add {{plant.productName}}</button>
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
data: () => ({
cart: [], // holds the referente to each item and quantity
plantList:[
{productName: 'flowers', quantity: 5},
{productName: 'cactus', quantity: 3},
{productName: 'trees', quantity: 6},
]
}),
methods: {
addPlant(plant){
// if the item is in the cart, add +1 to item
if(this.cart[plant.productName]) {
this.cart[plant.productName] += 1
return
}
// if the item is not in the cart, add it with 1 as quantity
this.cart[plant.productName] = 1
}
}
}
</script>
Source:stackexchange.com