这个案例是对前面基础知识的一个整合,用到的知识点还是挺多的,比如 filters 以及属性的动态绑定等。
2020-6-17 修改:求总价格时,换用高阶函数 reduce。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
thead {
background-color: rgb(243, 243, 243);
}
td,
th {
border: solid 1px rgb(226, 226, 226);
}
table {
border-collapse: collapse;
}
.end {
color: black;
font-size: 30px;
}
</style>
</head>
<body>
<div id="app">
<table>
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,key) in books">
<td>{{key+1}}</td>
<td>{{item.name}}</td>
<td>{{item.publish}}</td>
<td>{{item.price | singlePrice}}</td>
<td>
<button @click="decrement(key)" :disabled="item.count===1">-</button>
<button>{{item.count}}</button>
<button @click="increment(key)">+</button>
</td>
<td><button @click="remove(key)">移除</button></td>
</tr>
</tbody>
</table>
<div class="end">
<div v-if="books.length!==0">
总价格{{totalPrice}}
</div>
<div v-else> 购物车为空 </div>
</div>
</div>
<script src="vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
books: [{
name: '《算法导论》',
publish: '2006-9',
price: 85,
count: 1
},
{
name: '《UNIX编程艺术》',
publish: '2006-2',
price: 59,
count: 1
},
{
name: '《编程珠玑》',
publish: '2008-10',
price: 39,
count: 1
},
{
name: '《代码大全》',
publish: '2006-3',
price: 128,
count: 1
}
]
},
methods: {
increment(key) {
this.books[key].count++;
},
decrement(key) {
this.books[key].count--;
},
remove(key) {
this.books.splice(key, 1);
}
},
computed: {
totalPrice() {
//for in 遍历写法
// let sum = 0;
// for (let i in this.books) {
// sum += this.books[i].price * this.books[i].count;
// }
//高阶函数reduce写法
let sum = this.books.reduce((prev, item) => prev + item.price, 0);
return '¥' + sum.toFixed(2);
}
},
filters: {
singlePrice(value) {
return '¥' + value.toFixed(2);
}
}
})
</script>
</body>
</html>