用vue实列来实现购物车的单选多选功能,使用了v-for v- model 使用@change来代替了@click
我们要知道怎么实现这个需求具体要怎么实现呢?
点击每一个单选的情况,就判断arr和list的长度,
如果相等就说明全部选中了,就要把全选框勾上
如果不相等就要把全选框 取消勾选
话不多说代码如下:
这是页面的代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<div id="app">
<table border="1">
<thead>
<tr>
<th>
<input type="checkbox" v-model="allFlag" @change="checkall">
</th>
<th>id</th>
<th>商品名称</th>
<th>商品价格</th>
<th>商品数量</th>
<th>小计</th>
</tr>
</thead>
<tbody>
{{arr}}
<tr v-for="(item,index) in list" :key="item.id">
<td> <input type="checkbox" :value="item.id" v-model="arr" @change="single"> </td>
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>
<button :disabled="item.num<=1" @click="sub(item)">-</button>
{{item.num}}
<button @click="add(item)">+</button>
<button @click="del(index)">x</button>
</td>
<td>{{item.num*item.price}}</td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript" src="../lib/node_modules/vue/dist/vue.js"></script>
<script type="text/javascript">
const app = new Vue({
el: '#app',
data: {
msg: 'test',
allFlag: false, // 记录全选框的状态
arr: [], // 记录每一个单选的状态
list: [
{
id: '001',
name: 'HUAWEI',
price: 200,
num: 1
},
{
id: '002',
name: 'XIAOMI',
price: 100,
num: 3
}
]
},
methods: {
add(product) {
product.num++
// console.log(product)
// console.log('aaaaaaaaaaa')
},
sub(product) {
product.num--
},
del(idx) {
const flag = confirm('确定删除吗?')
if (flag) {
this.list.splice(idx, 1)
}
// alert('12')
// console.log(idx)
// this.list.splice(idx,1)
},
checkall() {
// console.log(this.allFlag)
if (this.allFlag) { // 全选选中的情况
for (let i = 0; i < this.list.length; i++) {
this.arr.push(this.list[i].id)
}
} else {
this.arr = []
}
},
single() {
// 点击每一个单选的情况,就判断arr和list的长度,
// 如果相等就说明全部选中了,就要把全选框勾上
// 如果不相等就要把全选框 取消勾选
// if(this.arr.length === this.list.length){
// this.allFlag = true
// }else{
// this.allFlag = false
// }
this.allFlag = this.arr.length === this.list.length
}
}
})
</script>