vue3 写一段购物车
时间: 2023-07-05 21:31:02 浏览: 80
好的,下面是一个简单的 Vue 3 购物车示例代码:
```vue
<template>
<div class="cart">
<h2>购物车</h2>
<div class="cart-items">
<div class="cart-item" v-for="(item, index) in items" :key="index">
<div class="cart-item__name">{{ item.name }}</div>
<div class="cart-item__price">¥{{ item.price }}</div>
<div class="cart-item__quantity">
<button @click="decrease(index)">-</button>
{{ item.quantity }}
<button @click="increase(index)">+</button>
</div>
<div class="cart-item__subtotal">小计:¥{{ item.subtotal }}</div>
<div class="cart-item__remove">
<button @click="remove(index)">删除</button>
</div>
</div>
</div>
<div class="cart-summary">
<div class="cart-summary__subtotal">商品总价:¥{{ subtotal }}</div>
<div class="cart-summary__shipping">运费:¥{{ shipping }}</div>
<div class="cart-summary__total">总价:¥{{ total }}</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: '商品1', price: 100, quantity: 1 },
{ id: 2, name: '商品2', price: 200, quantity: 2 },
{ id: 3, name: '商品3', price: 300, quantity: 3 }
],
shipping: 10
};
},
computed: {
// 计算商品总价
subtotal() {
return this.items.reduce((acc, item) => acc + item.subtotal, 0);
},
// 计算总价
total() {
return this.subtotal + this.shipping;
}
},
methods: {
// 增加商品数量
increase(index) {
this.items[index].quantity++;
},
// 减少商品数量
decrease(index) {
if (this.items[index].quantity > 1) {
this.items[index].quantity--;
}
},
// 删除商品
remove(index) {
this.items.splice(index, 1);
}
},
// 监听数据变化,重新计算小计
watch: {
items: {
handler(val) {
val.forEach(item => {
item.subtotal = item.price * item.quantity;
});
},
immediate: true,
deep: true
}
}
};
</script>
<style>
.cart {
border: 1px solid #ccc;
padding: 10px;
}
.cart h2 {
font-size: 24px;
margin-bottom: 10px;
}
.cart-items {
margin-bottom: 20px;
}
.cart-item {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid #ccc;
padding: 10px 0;
}
.cart-item__name {
font-size: 18px;
}
.cart-item__price {
font-size: 18px;
}
.cart-item__quantity {
display: flex;
align-items: center;
}
.cart-item__quantity button {
font-size: 18px;
padding: 5px 10px;
margin: 0 5px;
}
.cart-item__subtotal {
font-size: 18px;
}
.cart-item__remove {
font-size: 18px;
}
.cart-item__remove button {
color: red;
border: none;
background-color: transparent;
cursor: pointer;
}
.cart-summary {
display: flex;
justify-content: flex-end;
align-items: center;
font-size: 18px;
}
.cart-summary__subtotal {
margin-right: 20px;
}
</style>
```
这个购物车示例包含了商品列表、小计、总价等功能。用户可以增加或减少商品数量,也可以删除某个商品。在数据变化时,小计和总价会自动重新计算。
阅读全文