运行效果
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图书购物车案例</title>
<script src="../js/vuejs-2.5.16.js"></script>
<style>
*{
padding: 0px;
margin: 0px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
div{
margin-top: 60px;
margin-left:30%;
}
table{
border: 1px solid #e9e9e9;
border-collapse: collapse;
border-spacing: 0px;
}
th,td {
padding: 8px 16px;
border: 1px solid #e9e9e9;
text-align: left;
}
th{
background-color: #f7f7f7;
color: #5c6b77;
font-weight: 600;
}
</style>
</head>
<body>
<div id="app">
<table v-if="isNull">
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,indexBooks) in books">
<td>{{item.id}}</td>
<td>{{item.bookName}}</td>
<td>{{item.publishDate}}</td>
<td>{{item.bookPrice | showPrice}}</td>
<td>
<button @click="increase(indexBooks)" style="width: 18px">+</button>
{{item.purchaseQuantity}}
<button @click="decrease(indexBooks)" style="width: 18px">-</button>
</td>
<!--<td v-for="(value,index,key) in item">
<button @click="increase(indexBooks)" v-if="key === 4" style="width: 18px">+</button>
<span v-if="key === 3 ">{{ value |showPrice(indexBooks)}}</span>
<span v-else>{{value}}</span>
<button @click="decrease(indexBooks)" v-if="key === 4" style="width: 18px">-</button>
</td>-->
<td><button @click="remove(indexBooks)">移除</button></td>
</tr>
<tr>
<td>总价</td>
<td colspan="6">
{{totalPrice | showPrice}}
</td>
</tr>
</tbody>
</table>
<span v-else>购物车已经清空!</span>
</div>
</body>
<script>
const app = new Vue({
el: '#app',
data: {
isNull: true,
books:[
{
id: 1,
bookName:'《Java编程艺术》',
publishDate: '2016-08',
bookPrice: 99.9,
purchaseQuantity: 0
},
{
id: 2,
bookName:'《Linux编程艺术》',
publishDate: '2015-02',
bookPrice: 120.5,
purchaseQuantity:0
},
{
id: 3,
bookName:'《代码大全》',
publishDate: '2014-05',
bookPrice: 112.7,
purchaseQuantity:0
},
{
id: 4,
bookName:'《PHP从入门到精通》',
publishDate: '2018-09',
bookPrice: 165.6,
purchaseQuantity:0
}
]
},
filters: {
showPrice(bookPrice){
return '¥'+ bookPrice.toFixed(2)
}
},
computed:{
totalPrice:{
get() {
let totalPrice = this.books.reduce((pre,book) => pre + book.bookPrice * book.purchaseQuantity,0)
return totalPrice
}
}
},
methods:{
increase(indexBooks){
this.books[indexBooks].purchaseQuantity++
},
decrease(indexBooks) {
if (this.books[indexBooks].purchaseQuantity > 0) {
return this.books[indexBooks].purchaseQuantity--
} else {
return this.books[indexBooks].purchaseQuantity = 0
}
},
remove(indexBooks){
this.books.splice(indexBooks,1)
if(this.books == null || this.books == ''){
return this.isNull = !this.isNull
}
},
}
})
</script>
</html>