<!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>购物车</title>
<link rel="stylesheet" href="//unpkg.com/layui@2.6.8/dist/css/layui.css">
</head>
<body>
<div id="app">
<div v-if="contents.length">
<table class="layui-table" lay-size="lg">
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(values,index) in contents">
<td>{{values.id}}</td>
<td>{{values.name}}</td>
<td>{{values.date}}</td>
<td>{{values.price | formatPrice}}</td>
<td>
<button @click="sub(index)" class="layui-btn" :disabled="values.count <= 1">-</button>
<span>{{values.count}}</span>
<button @click="add(index)" class="layui-btn">+</button>
</td>
<td>
<button class="layui-btn layui-btn-radius layui-btn-danger" @click="removeHandle(index)">移除</button>
</td>
</tr>
</tbody>
</table>
</div>
<h1 v-else>
购物车为空
</h1>
<div>
总价格:<span>{{totalPrice | formatPrice}}</span>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
contents: [
{id: 1,name: '《算法导论》',date: '2006-9',price: 85,count: 1},
{id: 2,name: '《UNIX编程艺术》',date: '2006-2',price: 59,count: 1},
{id: 3,name: '《编程珠玑》',date: '2008-10',price: 39,count: 1},
{id: 4,name: '《代码大全》',date: '2006-3',price: 128,count: 1},
]
},
methods: {
add(index) {//增加购物车项目数量
this.contents[index].count ++
},
sub(index) {//减少购物车项目数量
this.contents[index].count --
},
removeHandle(index) {//删除购物车项目
this.contents.splice(index,1)
}
},
computed: {
totalPrice() {//购物车总价格
return this.contents.reduce(function(pre,n) {
return pre + n.count * n.price
},0)
}
},
filters: {
formatPrice(price) {
return '¥' + price.toFixed(2)
}
}
})
</script>
</body>
</html>
Vue购物车案例(初学版)
最新推荐文章于 2022-03-15 15:35:42 发布