效果图:
<!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>简单的书籍购物车案例</title>
<style type="text/css">
h3 {
text-align: center;
}
table {
border-collapse: collapse;
border-spacing: 0;
border: 1px solid #e9e9e9;
}
th,
td {
padding: 8px 16px;
text-align: center;
border: 1px solid #e9e9e9;
}
thead {
background: #f6f6f6;
}
</style>
</head>
<body>
<div id="app">
<div v-if="books.length">
<table>
<caption>
<h2>书籍购物车案例</h2>
</caption>
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in books" :key="index">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.time}}</td>
<!-- <td>{{'¥' + item.price.toFixed(2)}}</td> -->
<!-- <td>{{getPrice(item.price)}}</td> -->
<td>{{item.price | showPrice}}</td>
<td>
<button @click="decrement(index)" :disabled="item.count == 0">
-
</button>
{{item.count}}
<button @click="incrment(index)">+</button>
</td>
<td><button @click="removeHandle(index)">操作</button></td>
</tr>
</tbody>
</table>
<h4>总价格:{{totalPrice | showPrice}}</h4>
</div>
<h3 v-else>购物车为空</h3>
</div>
<script src="js/vue.js"></script>
<script>
var app = new Vue({
el: "#app",
data: {
books: [{
id: 1,
name: "《算法导论》",
time: "2019-11",
price: 85,
count: 1,
},
{
id: 2,
name: "《UNIX编程艺术》",
time: "2019-12",
price: 36,
count: 1,
},
{
id: 3,
name: "《编程珠玑》",
time: "2019-14",
price: 120,
count: 1,
},
{
id: 4,
name: "《代码大全》",
time: "2019-15",
price: 45,
count: 1,
},
],
},
// 过滤器
filters: {
showPrice: function (price) {
return "¥" + price.toFixed(2);
},
},
// 计算属性
computed: {
totalPrice: function () {
let totalprice = 0;
// for(let i=0; i < this.books.length; i++){
// totalprice += this.books[i].price * this.books[i].count
// }
// for(let i in this.books){
// totalprice += this.books[i].price * this.books[i].count
// }
// for(let item of this.books){
// totalprice += item.price * item.count
// }
// return totalprice;
return this.books.reduce(function (prev, cur) {
return prev + cur.price * cur.count;
}, 0);
},
},
methods: {
getPrice: function (price) {
return "¥" + price.toFixed(2);
},
// 操作 删除
removeHandle: function (index) {
this.books.splice(index, 1);
},
// 减少
decrement: function (index) {
this.books[index].count--;
},
// 增加
incrment: function (index) {
this.books[index].count++;
},
},
});
</script>
</body>
</html>