最终效果
需求分析
- 列表显示id号、书名、出版时间、价格、购买数量、删除等信息和操作按钮;
- 点击+、-实现增加或减少购买数量,且当购买数量减少到0时隐藏’-'按钮;
- 点击移除按钮实现从购物车删除该书的信息;
- 计算购物车中所有书的总价
实现效果
-
显示书籍信息和总价信息
-
增加/减少购买数量,总价也随之改变
-
删除不想购买的书,总价也随之改变
补充:
filters(过滤器),如:
效果:
disabled(禁用效果),如
实现代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>5图书购物车小测试</title>
<style>
.hide{
display: none;
}
table{
border-color: #e9e9e9;
border-collapse: collapse;
}
caption{
margin-bottom: 10px;
}
thead{
background-color: #f7f7f7;
color: #5c6b77;
font-weight: bold;
}
th, td{
padding: 8px 16px;
border: 1px solid #e9e9e9;
text-align: left;
}
</style>
</head>
<body>
<div id="info" :class="{hide: books.length === 0}">
<table cellspacing="0" border="1">
<caption>图书购物车</caption>
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(b,index) in books">
<td>{{b.id}}</td>
<td>{{b.name}}</td>
<td>{{b.time}}</td>
<td>{{b.price | showPrice}}</td>
<td>
<button @click="sub(index)" :class="{hide: b.num === 0,}" :disabled="b.num <= 1">-</button>
{{b.num}}
<button @click="add(index)">+</button>
</td>
<td>
<button @click="remove(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<p>总价:{{sumPrice | showPrice}}</p>
</div>
<script src="../../js/vue.js"></script>
<script>
const info = new Vue({
el : "#info",
data : {
books :[
{id: 1, name: "《算法导论》", time: '2006-9', price: 85.00, num: 1},
{id: 2, name: "《UNIX编程艺术》", time: '2006-2', price: 59.00, num: 1},
{id: 3, name: "《编程珠玑》", time: '2008-10', price: 39.00, num: 1},
{id: 4, name: "《代码大全》", time: '2006-3', price: 128.00, num: 1},
]
},
computed: {
sumPrice() {
let sump = 0;
for (let i of this.books){
sump += i.price * i.num;
}
return sump;
}
},
filters: {//过滤器
showPrice(price){
return '¥' + price.toFixed(2);
}
},
methods : {
add: function (index) {
this.books[index].num++;
},
sub: function (index) {
if(this.books[index].num > 0)
this.books[index].num--;
},
remove: function (index) {
this.books.splice(index,1);
},
}
})
</script>
</body>
</html>