十二、Vue 实现 购物车demo
1. html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="app">
<div v-if="books.length">
<table>
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in books">
<td> {{ item.id }} </td>
<td> {{ item.name }} </td>
<td> {{ item.date }} </td>
<!-- <td> {{ getFinalPrice(item.price) }} </td> -->
<!-- <td> {{ item.price | 过滤器 }} </td> -->
<td> {{ item.price | showPrice }}
<td>
<button @click="increment(index)">+</button>
{{ item.sumNumber }}
<button @click="decrement(index)" v-bind:disabled="item.sumNumber<=1">-</button>
</td>
<td> <button @click="removeHandle(index)">移除</button> </td>
</tr>
</tbody>
</table>
<h2>总价格:{{ totalSumPrice | showPrice }}</h2>
</div>
<div v-else>
<h2>购物车为空</h2>
</div>
</div>
<script src="../jquery/vue.JS"></script>
<script src="main.js"></script>
</body>
</html>
2. css代码
table{
border: 1px solid #e9e9e9;
border-collapse: collapse;
border-spacing: 0;
}
th, td{
padding: 8px 16px;
border: 1px solid #e9e9e9;
text-align: center;
}
th{
background-color: #f7f7f7;
color: #5c6b77;
font-weight: 600;
}
3. js代码
const app = new Vue({
el: "#app",
data: {
books: [
{id: 1, name: "《算法导论》", date: "2006-9", price: 85.00, sumNumber:1},
{id: 2, name: "《UNIX编程艺术》", date: "2006-2", price: 59.00, sumNumber:1},
{id: 3, name: "《变成注记》", date: "2008-10", price: 39.00, sumNumber:1},
{id: 4, name: "《代码大全》", date: "2006-3", price: 128.00, sumNumber:1},
],
},
methods: {
// getFinalPrice(price){
// return "¥" + price.toFixed(2);
// },
increment(index){
this.books[index].sumNumber++;
},
decrement(index){
this.books[index].sumNumber--;
},
removeHandle(index){
this.books.splice(index,1);
}
},
computed: {
totalSumPrice(){
let totalprice = 0;
// //1. 普通的for循环
// for(let i=0; i<this.books.length; i++){
// totalprice += this.books[i].sumNumber * this.books[i].price;
// }
// //2. for(let i in this.books){}
// for(let i in this.books){
// totalprice += this.books[i].sumNumber * this.books[i].price;
// }
// //3. for(let i of this.books){}
// for(let book of this.books){
// totalprice += book.sumNumber * book.price;
// }
// return totalprice;
//4. reduce
return this.books.reduce(function(preValue,book){
return preValue + book.sumNumber * book.price;
},0)
}
},
filters: {
//过滤器、一般为函数
showPrice(price){
return "¥" + price.toFixed(2);
}
}
});

浙公网安备 33010602011771号