<!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>Document</title>
<style>
td{
padding: 5px;
border: solid 1px;
}
.sum{
font-size: 20px;
font-weight: 800;
}
</style>
</head>
<body>
<div id="app">
<div v-if="book.length">
<table>
<tr>
<td></td>
<td>书籍名称</td>
<td>出版日期</td>
<td>价格</td>
<td>购买数量</td>
<td>操作</td>
</tr>
<tr v-for="(item,index) in book">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.data}}</td>
<td>{{item.price | showPrice}}</td>
<td>
<button @click="decrement(index)" :disabled="item.num<=1">-</button>
{{item.num}}
<button @click="increment(index)">+</button>
</td>
<td>
<button @click="remove(index)">移除</button>
</td>
</tr>
</table>
<div class="sum">总价格:
<span>{{total | showPrice}}</span>
</div>
</div>
<div v-else>购物车清空</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
var app=new Vue({
el:'#app',
data:{
book:[
{
id:1,
name:"《aaa》",
data:"2006-9",
price:85.00,
num:1
},
{
id:2,
name:"《bbb》",
data:"2006-9",
price:85.00,
num:1
},
{
id:3,
name:"《ccc》",
data:"2006-9",
price:85.00,
num:1
},
{
id:4,
name:"《ddd》",
data:"2006-9",
price:85.00,
num:1
}
],
},
filters:{ //过滤器
showPrice(price){
return '¥' + price.toFixed(2)
}
},
methods:{
decrement:function(index){
this.book[index].num--;
},
increment:function(index){
this.book[index].num++;
},
remove:function(index){
this.book.splice(index,1);
}
},
computed:{
total(){
let total=0;
for(let i=0;i<this.book.length;i++){
total+=this.book[i].price*this.book[i].num;
}
return total;
}
}
})
</script>
</body>
</html>
简单购物车案例 Vue
最新推荐文章于 2021-12-21 16:10:08 发布