需要实现的功能:
点击"+"按钮,总价增加,点击"-"按钮总价减少,点击移除,移除当列。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
#app{
margin-left:500px;
}
table {
border: 2px solid red;
width: 500px;
border-collapse: collapse;
}
td {
border: 2px solid red;
padding-top: 10px;
}
.a{
margin-top: 20px;
margin-left:350px;
font-size: 20px;
}
tr{
text-align: center;
}
</style>
</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>
</tr>
</thead>
<tbody>
<tr v-for="(values,index) in contents">
<td>{{values.id}}</td>
<td>{{values.name}}</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 class="a">总价格:<span>{{totalPrice | formatPrice}}元</span></div>
</div>
<script src="vue.js"></script>
<script type="text/javascript">
new Vue({
el: '#app',
data: {
contents: [
{id: 1,name:'《语文》',price: 200,count: 1},
{id: 2,name:'《数学》',price: 100,count: 1},
{id: 3,name:'《英语》',price: 160,count: 1},
{id: 4,name:'《体育》',price: 500,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)
}
},
})
</script>
</body>
</html>