Vue-购物车案例
需求
实现购物车效果
- 修改数量, 总价格会实时计算
- 点击按钮移除书籍
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="./node_modules/vue/dist/vue.global.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
#app {
margin: 50px;
width: 500px;
height: 250px;
border: 2px dashed black;
}
table {
border: 2px, solid, black;
width: 480px;
height: 160px;
line-height: 25px;
margin: auto;
}
th, td {
border: 1px, solid, black;
}
#totalprice {
text-align: right;
}
</style>
</head>
<body>
<div id="app">
<table>
<caption>购物车</caption>
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(product, index) in products" :key="product.id">
<td>{{ index + 1 }}</td>
<td>{{ product.name }}</td>
<td>{{ product.date }}</td>
<td>¥{{ product.price.toFixed(2) }}</td>
<td>
<button @click="reduceQuantity(index)">-</button>{{ product.quantity}}<button @click="addQuantity(index)">+</button>
</td>
<td>
<button @click="removeProduct(index)">移除</button>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="6" id="totalprice">总价格: ¥{{ totalprice.toFixed(2) }}</td>
</tr>
</tfoot>
</table>
</div>
<script>
const { createApp } = Vue
const vm = createApp({
data() {
return {
products: [
{ id: 1, name: '算法导论', date: '2006-09', price: 85.00, quantity: 2 },
{ id: 2, name: 'Unix编程艺术', date: '2006-02', price: 59.00, quantity: 2 },
{ id: 3, name: '编程珠玑', date: '2008-10', price: 39.00, quantity: 2 }
]
}
},
computed: {
totalprice() {
return this.products.reduce(
(total, product) => {
return total + product.price * product.quantity;
}, 0)
}
},
methods: {
removeProduct(index) {
this.products.splice(index, 1);
},
reduceQuantity(index) {
if (this.products[index].quantity > 1) {
this.products[index].quantity--
}
},
addQuantity(index) {
this.products[index].quantity++
},
}
}).mount('#app')
</script>
</body>
</html>