一、需求说明:
- 实现页面基本布局。
- 单击“+”按钮时,对应商品的数量增加,当单击“-”按钮时,对应商品的数量减少,当数量减少到1时,“-”按钮无法再进行操作。
- 每个对应商品后面都有一个“移除”按钮,当单击“移除”按钮时,当前商品列表项会删除,页面效果图如下:
二、实现过程:
HelloWorld.vue代码示例:
<template>
<div>
<table id="mytable">
<thead>
<tr style="background: Gainsboro;">
<th></th>
<th>商品名称</th>
<th>商品单价</th>
<th>商品数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in goods" :key="index" :class="{on:index%2!==0,off:index%2==0}">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>
<button @click="reduce(index)">-</button> {{item.count}} <button @click="add(index)">+</button>
</td>
<td>
<button @click="del(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<p>总价:¥ {{sum}}</p>
</div>
</template>
<script>
export default {
name:'HelloWorld',
data(){
return{
goods:[
{
id:1,
name:"IPhone X",
price:7999,
count:1
},
{ id:2,
name:"荣耀16",
price:2399,
count:1
},
{ id:3,
name:"华为P22",
price:3399,
count:1},
{ id:4,
name:"小米9",
price:3999,
count:1},
]
}
},
methods:{
reduce(index){
if(this.goods[index].count==1){
this.goods[index].count=1
}else{
this.goods[index].count--;
}
},
add(index){
this.goods[index].count++;
},
del(index){
this.goods.splice(index,1)
}
},
computed:{
sum:function(){
var sum=0;
for(var i=0;i<this.goods.length;i++){
sum+=this.goods[i].price*this.goods[i].count;
}
return sum;
}
}
}
</script>
<style>
table{
border: 1px solid gray;
width:600px;
border-collapse:collapse;
}
tr{
height: 35px;
text-align: center;
}
.on{
background: #F5F5F5;
}
.off{
background:white;
}
</style>