帮我写一个好看的购物车页面vue
时间: 2024-05-29 21:03:34 浏览: 21
好的,下面是一个简单的购物车页面的 Vue 代码:
```
<template>
<div class="cart">
<h1>购物车</h1>
<div v-if="cartItems.length === 0">
<p>购物车是空的</p>
</div>
<div v-else>
<table>
<thead>
<tr>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in cartItems" :key="index">
<td>{{ item.name }}</td>
<td>{{ item.price }}</td>
<td>
<button @click="decreaseQuantity(index)" :disabled="item.quantity === 1">-</button>
{{ item.quantity }}
<button @click="increaseQuantity(index)">+</button>
</td>
<td>{{ item.quantity * item.price }}</td>
<td>
<button @click="removeItem(index)">删除</button>
</td>
</tr>
</tbody>
</table>
<div class="total">
<p>共 {{ totalQuantity }} 件商品,总计 {{ totalPrice }} 元</p>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
cartItems: [
{ name: '商品1', price: 10, quantity: 1 },
{ name: '商品2', price: 20, quantity: 2 },
{ name: '商品3', price: 30, quantity: 3 }
]
};
},
computed: {
totalQuantity() {
return this.cartItems.reduce((total, item) => total + item.quantity, 0);
},
totalPrice() {
return this.cartItems.reduce((total, item) => total + item.quantity * item.price, 0);
}
},
methods: {
decreaseQuantity(index) {
this.cartItems[index].quantity--;
},
increaseQuantity(index) {
this.cartItems[index].quantity++;
},
removeItem(index) {
this.cartItems.splice(index, 1);
}
}
};
</script>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}
button {
margin: 0 4px;
}
.total {
margin-top: 16px;
text-align: right;
font-weight: bold;
}
</style>
```
这个购物车页面包含了以下功能:
- 显示购物车中的商品名称、单价、数量和小计
- 可以增加或减少某个商品的数量
- 可以从购物车中删除某个商品
- 显示购物车中商品的总数量和总价格
你可以根据自己的需求进行修改和扩展。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)