当将商品添加到购物车时,您需要某种方式来指定特定商品的数量,按照它的实现方式,您添加了一个数量,但没有告知哪个商品。
要解决这个问题,请创建一个数组作为购物车,并在购物车中添加与产品相关的数量。
此外,当显示每个商品的数量时,您必须根据购物车上的商品标识来显示它(在下面的示例中,我使用名称作为标识)。这就是问题所在,你表现出了同样的价值(
stock
)到所有项目。
以下是工作的方式。
<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: [],
plantList:[
{productName: 'flowers', quantity: 5},
{productName: 'cactus', quantity: 3},
{productName: 'trees', quantity: 6},
]
}),
methods: {
addPlant(plant){
if(this.cart[plant.productName]) {
this.cart[plant.productName] += 1
return
}
this.cart[plant.productName] = 1
}
}
}
</script>
Live demo here