<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>书籍购物车案例</title>
<script src="vue.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css">
h3{
text-align: center;
}
table {
border-collapse: collapse;
border-spacing: 0;
border: 1px solid #e9e9e9;
margin: 0 auto;
}
th,
td {
padding: 8px 16px;
text-align: center;
border: 1px solid #e9e9e9;
}
thead {
background: #F6F6F6;
}
</style>
</head>
<body>
<!-- 遍历、过滤器、数组方法 -->
<div class="test">
<h3>书籍购物车案例</h3>
<table v-if="books.length">
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<!-- <tr v-for="item in books">
<td v-for="val in item">{{val}}</td>
</tr> -->
<tr v-for="(item,index) in books">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.time}}</td>
<td>{{item.price | priceadd}} </td>
<td><button :disabled="item.count==0" @click="cut(index)">-</button> {{item.count}} <button @click="add(index)">+</button></td>
<td><button type="button" @click="remove(index)">移除</button></td>
</tr>
<tr><td colspan="6">价格:{{totalprice | priceadd}}</td></tr>
</tbody>
</table>
<div v-else>购物车为空</div>
</div>
<script type="text/javascript">
let test = new Vue({
el:'.test',
data:{
books:[
{id:1,name:'《算法导论》',time:'2019-11',price:85,count:1},
{id:2,name:'《UNIX编程艺术》',time:'2019-12',price:36,count:1},
{id:3,name:'《编程珠玑》',time:'2019-14',price:120,count:1},
{id:4,name:'《代码大全》',time:'2019-15',price:45,count:1}
]
},
computed:{
totalprice: function(){
let totalprice = 0;
for(let item of this.books){
totalprice += item.price * item.count
}
// for(let i in this.books){
// totalprice += this.books[i].price * this.books[i].count
// }
// for(let i = 0; i<this.books.length;i++){
// totalprice += this.books[i].price * this.books[i].count
// }
return totalprice
}
},
methods:{
cut: function(index){
this.books[index].count--
},
add: function(index){
this.books[index].count++
},
remove: function(index){
this.books.splice(index,1)
}
},
filters:{
priceadd: function(price){
return '¥' + price.toFixed(2)
}
}
})
</script>
</body>
</html>
书籍购物车案例
最新推荐文章于 2022-11-22 19:15:31 发布