'Problem with shopping cart, adding products, in vuejs
I have a problem with my shopping cart: when I want to add a product to the cart my function adds one product of each product available. (I hope this is clear enough since english is not my first language)
<h3>Product list</h3>
<ul>
<li>
{{plants.productName}} : {{plants.quantity}}
</li>
</ul>
</div>
<br><br>
<div>
<h3>Shopping list:</h3>
<ul>
<li v-for="plant in plantList">
{{plant.productName}} : {{stock}}
<button @click="addPlant">Add {{plant.productName}}</button>
<!--<span v-if="plant.quantity === 0">No stock</span>
-->
</li>
</ul>
</div>
</div>
<script>
const app=new Vue({
el: '#app',
data: {
stock: 0,
plantList:[
{productName: 'flowers', quantity: 5},
{productName: 'cactus', quantity: 3},
{productName: 'trees', quantity: 6},
]
},
methods: {
addPlant(){
this.stock += 1;
}
})
</script>
I just want to add one product when I click the button
Solution 1:[1]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Luis de Brito |
