<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
table{
text-align: center;
}
td{
display: inline-block;
width:100px;
height: 25px;
}
</style>
</head>
<body>
<div class="app">
<table border="" cellspacing="0" cellpadding="0">
<thead>
<tr>
<td></td>
<td>名称</td>
<td>出版日期</td>
<td>价格</td>
<td>购买数量</td>
<td>操作</td>
</tr>
</thead>
<tbody>
<!-- v-if="item.count !== 0" 当图书数量为0时自动移除 -->
<tr v-for="(item,index) in books" v-if="item.count !== 0">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<td>{{item.price | showPrice}}</td>
<td>
<button type="button" @click="sub(index)" :disabled="item.count<=0">-</button>
{{item.count}}
<button type="button" @click="add(index)">+</button>
</td>
<td><button type="button" @click="remove">移除</button></td>
</tr>
</tbody>
</table>
<!-- {{allPrice | showPrice}}将allPrice作为参数传到showPrice中 -->
<h2>总价格:{{allPrice | showPrice}}</h2>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascript">
const test = new Vue({
el:".app",
data:{
books:[
{
id:1,
name:'java',
date:'2000',
price:20,
count:1
},
{
id:2,
name:'c++',
date:'2001',
price:28,
count:1
},
{
id:3,
name:'c',
date:'2020',
price:33,
count:1
},
{
id:4,
name:'js',
date:'1998',
price:20,
count:1
},
]
},
methods:{
// 增加图书数量
add(index){
this.books[index].count++;
},
// 减少图书数量
sub(index){
this.books[index].count--;
},
// 移除图书
remove(index){
this.books.splice(index,1);
}
},
//过滤器
filters:{
showPrice(price){
return '$' + price.toFixed(2);
}
},
computed:{
//计算总价格
allPrice(){
// let allP = 0;
// for(let book of this.books){
// allP += book.price * book.count;
// }
// return allP;
// 高阶函数reduce的使用
let allP = this.books.reduce(function(price,book){
return price + book.price * book.count;
},0);
return allP;
}
}
})
</script>
</body>
</html>
本文最后更新于2020年03月17日,已经过了1767天没有更新,若内容或图片失效,请留言反馈
text 代码:
声明:本文由 yuan(博主)原创,依据 CC-BY-NC-SA 4.0 许可协议 授权,转载请注明出处。