初始值和选中值用v-model绑定
<el-checkbox-group v-model="items1" @change="handleCheckedCitiesChange">
//值从父级里面循环出来
<template v-for="item in items">
<el-checkbox :label="item.id" :key="item.id" style="display:block;margin-bottom:15px" :class="item.child.length !== 0 ? 'box' : ''">
{{ item.name }}
//判断有子级的,用另一组多选框插入显示,调整一下样式
<template v-if="item.child.length != 0">
<div style="margin-top:15px">
//值从子级里面循环出来
<el-checkbox v-for="item in item.child" :label="item.id" :key="item.id" class="box2">{{ item.name }}</el-checkbox>
</div>
</template>
</el-checkbox>
</template>
</el-checkbox-group>
进入页面如果有数据,判断全选状态和不稳定状态
全选为请求回来的已选中的值等于请求回来的所有选项。 items1为已有,items2为所有项
this.checkAll = this.items2.length === this.items1.length;
不稳定状态为请求回来的已选中的值小于请求回来的所有选项并且大于0
this.isIndeterminate = this.items1.length > 0 && this.items1.length < this.items2.length;
//全选方法
handleCheckAllChange(val) {
let items = [];
this.items.forEach((t) => {
items.push(t.id);
if (t.child.length !== 0) {
t.child.forEach((t) => {
items.push(t.id);
});
}
});
//设定选中值
this.items1 = val ? items : [];
//设定不稳定状态
this.isIndeterminate = false;
}
单选方法,主要设定全选态和不稳定状态
handleCheckedCitiesChange(value) {
let checkedCount = value.length;
this.checkAll = checkedCount === this.items2.length;
this.isIndeterminate = checkedCount > 0 && checkedCount < this.items2.length;
}
子级多选框的样式
.boxmain::v-deep {
.box {
.el-checkbox__input {
//设置定位,调整样式
position: relative;
top: -35px;
}
.box2 {
.el-checkbox__input {
//设置定位
position: relative;
top: 0px;
}
}
}
}