<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>购物车案例</title>
<style>
th,td{
border:1px solid red
}
</style>
</head>
<body>
<div id="app">
<div v-if="books.length!=0">
<table>
<thead>
<tr>
<th>序号</th>
<th>书籍名称</th>
<th>书记价格</th>
<th>书籍数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(book,index) in books" >
<td>{{index+1}}</td>
<td>{{book.name}}</td>
<td>{{book.price | show}}</td>
<td>
<button @click="decrement(index)" :disabled="book.number<=1">-</button>
{{book.number}}
<button @click="increment(index)">+</button>
</td>
<td><button @click="remove(index)">移除</button></td>
</tr>
</tbody>
</table>
<h2>总价格:{{totalPrice | show}}</h2>
</div>
<span v-else>购物车为空</span>
</div>
<script src="js/vue.js"></script>
<script>
let app = new Vue({
el: '#app',
data: {
message: 'HelloWorld',
books:[
{
id:1,
name:'Linux',
price:40.00,
number:1
},
{
id:2,
name:'Java',
price:50.00,
number:1
},
{
id:3,
name:'C++',
price:30.00,
number:1
}
]
},
methods:{
increment(index){
this.books[index].number++;
},
decrement(index){
this.books[index].number--;
},
remove(index){
this.books.splice(index,1)
}
},
//过滤器,处理价格显示
filters:{
show(price){
return '¥'+price.toFixed(2);
}
},
computed:{
totalPrice(){
// let result=0;
// for(let book of this.books){
// result += book.price * book.number;
// }
// return result;
// for的进阶
return this.books.reduce(function (preva,cur) {
return preva + cur.price * cur.number;
},0)
}
}
});
</script>
</body>
</html>
上述新增了过滤器+按钮的禁用+for的进阶
结果图: