vue购物车添加商品数量
时间: 2023-05-28 21:01:25 浏览: 142
如下是一个简单的示例,演示如何实现Vue购物车添加商品数量:
HTML代码:
```
<div id="app">
<h1>购物车</h1>
<ul>
<li v-for="product in products">
{{ product.name }} - ¥{{ product.price }}
<button @click="addToCart(product)">添加到购物车</button>
<span v-if="cart.includes(product.id)">
数量:<button @click="decreaseQuantity(product)">-</button>{{ cartQuantity[product.id] }}
<button @click="increaseQuantity(product)">+</button>
</span>
</li>
</ul>
</div>
```
Vue代码:
```
new Vue({
el: '#app',
data: {
products: [
{ id: 1, name: '商品1', price: 100 },
{ id: 2, name: '商品2', price: 200 },
{ id: 3, name: '商品3', price: 300 }
],
cart: [], // 购物车中商品ID的列表
cartQuantity: {} // 购物车中每个商品的数量
},
methods: {
addToCart(product) {
if (!this.cart.includes(product.id)) {
this.cart.push(product.id);
this.cartQuantity[product.id] = 1;
} else {
this.cartQuantity[product.id]++;
}
},
increaseQuantity(product) {
this.cartQuantity[product.id]++;
},
decreaseQuantity(product) {
if (this.cartQuantity[product.id] > 1) {
this.cartQuantity[product.id]--;
} else {
this.cart.splice(this.cart.indexOf(product.id), 1);
delete this.cartQuantity[product.id];
}
}
}
})
```
在这个示例中,我们创建了一个Vue实例,其中包含了一个`products`数组,以及两个空数组`cart`和`cartQuantity`。然后我们定义了三个方法:`addToCart`、`increaseQuantity`和`decreaseQuantity`。
当用户点击“添加到购物车”按钮时,`addToCart`方法会将商品ID添加到`cart`列表中,并将该商品的数量设为1。如果用户再次添加同样的商品,则只是数量加1。
在购物车列表中,我们检查该商品的ID是否包含在`cart`数组中,如果包含,则显示该商品的数量,并提供增加和减少数量的按钮。`increaseQuantity`和`decreaseQuantity`方法用于增加或减少商品数量,并且在数量减少到0时会将该商品从购物车中移除。