图书馆购物车
一、基本版面的实现
二、功能的实现
1、添加书籍
2 、移出书籍,移出完毕,显示购物车为空
3、计算总价
一、版面的实现
html代码
<div class='app'>
<div class="box" v-if='book.length'>
<table>
<thead>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</thead>
<tbody>
<tr v-for='(item,index) in book'>
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<td>{{item.price| showprice}}</td>
<td>
<button @click='decreament(index)' :disabled="item.num <= 1">-</button>
{{item.num}}
<button @click='increament(index)'>+</button>
</td>
<td><button @click='move(index)'>移出</button>
</td>
</tr>
</tbody>
</table>
</div>
<h3 v-else>购物车为空</h3>
<br>
<h3>总价:{{totalprice |showprice}}</h3>
</div>
vue代码
book: [
{
id: '1',
name: "《算法导论》",
date: "2006-9",
price: 85.00,
num: 1
},
{
id: '2',
name: "《UNIX编程艺术》",
date: "2006-2",
price: 59.00,
num: 1
},
{
id: '3',
name: "《编程珠玑》",
date: "2008-10",
price: 39.00,
num: 1
},
{
id: '4',
name: "《代码大全》",
date: "2006-3",
price: 128.00,
num: 1
}
],
将price显示为整数后有两位小数,涉及到了过滤器的使用
filters: {
showprice(price) {
return '¥' + price.toFixed(2)
}
}
二、功能的实现
1、书籍数量的加减,同时书籍的数量低于1本时,按钮便不能使用
increament(index) {
return this.book[index].num++;
},
decreament(index) {
return this.book[index].num--;
},
数量低于一本,动态添加disabled属性
:disabled="item.num <= 1"
2、移除,当数量为0时,界面显示购物车为空,
move(index) {
return this.book.splice(index, 1)
}
//显示为空,
在界面使用v-if,v-else
3、总价的计算,计算属性的使用
totalprice() {
let price = 0
for (let i = 0; i < this.book.length; i++) {
price += this.book[i].price * this.book[i].num
}
return price
}