1.当全部商品被勾选时 全选选择框会自动勾选
2.购买数量可输入 通过长按可实现连续加减1
3.总价和购买数量随着选择自动发生变化
代码如下:
<template>
<div>
<table v-if="list.length">
<thead>
<th>全选<input type="checkbox" name="" id="" :checked="isAllchecked" @change="AllCheck"></th>
<th>商品名称</th>
<th>商品单价</th>
<th>购买数量</th>
<th>操作</th>
</thead>
<tr v-for="(value,index) in list" :key="index">
<td><input type="checkbox" :checked='value.isChecked' @change="isCheck(index)"></td>
<td>{{value.name}}</td>
<td>{{value.price}}</td>
<td>
<button @click="handleReduce(index)" @mousedown="longReduce(index)" @mouseup="stopReduce">-</button>
<input type="input" v-model="value.count" class="input"/>
<button @click="handleAdd(index)" @mousedown="longAdd(index)" @mouseup="stopReduce">+</button>
</td>
<td>
<button @click="handleRemove(index)">删除</button>
</td>
</tr>
<tfoot>
<th colspan="5">
购买数量:{{totalNum}}
总价为:¥{{totalPrice}}
</th>
</tfoot>
</table>
<div v-else>
购物车为空
</div>
</div>
</template>
<script>
export default {
name:'ShoppingCart',
data(){
return{
timeOutEvent:'',
isAllchecked:false,
list:[
{
name:'iPhone 7',
price:6188,
count:1,
isChecked:true
},
{
name:'三星999',
price:8765,
count:1,
isChecked:false
},
{
name:'华为Pro11',
price:3999,
count:1,
isChecked:false
},
{
name:'华为荣耀',
price:5599,
count:1,
isChecked:false
}
]
}
},
computed: {
totalPrice:function(){
let total=0;
for(let item of this.list){
if(item.isChecked===true){
total+=item.price*item.count
}
}
return total
},
totalNum:function(){
let total=0;
for(let item of this.list){
if(item.isChecked===true){
total+=item.count
}
}
return total
}
},
methods: {
handleReduce(index){
if(this.list[index].count>1){
this.list[index].count--;
}
},
handleAdd(index){
this.list[index].count++;
},
handleRemove(index){
this.list.splice(index,1)
},
AllCheck(){
this.isAllchecked=!this.isAllchecked;
if(this.isAllchecked===true){
for(let item of this.list){
item.isChecked=true
}
}else{
for(let item of this.list){
item.isChecked=false
}
}
},
isCheck(index){
this.list[index].isChecked=!this.list[index].isChecked;
let flag=true;
for(let item of this.list){
if(item.isChecked===false){
flag=false
}
}
this.isAllchecked=flag
},
// 长按加一
longAdd(index){
this.timeOutEvent=setInterval(() => {
this.list[index].count++;
}, 300);
},
longReduce(index){
this.timeOutEvent=setInterval(() => {
if(this.list[index].count>1)
this.list[index].count--
}, 300);
},
stopReduce(){
clearInterval(this.timeOutEvent)
}
},
}
</script>
<style>
table{
width: 100%;
text-align: center;
border-collapse: collapse;
}
table,th,td{
border: 1px solid black;
}
th{
background-color: rgb(126, 150, 56);
height: 50px;
}
tr{
height: 50px;
}
tr:nth-child(odd){ /*双数变色用even*/
background-color: #EAF2D3;
}
.input{
width: 20px;
text-align: center;
}
/* tr:nth-child(even){background-color: #EAF2D3} */
</style>