1、html部分
<div v-for="(item, index) in data" :key="index">
<el-checkbox
style="margin-left: 30px"
:indeterminate="item.isIndeterminate"
v-model="item.isCheck"
@change="checkTitle(item.isCheck, index)"
>全选</el-checkbox
>
<el-checkbox-group
v-model="item.checkedData"
@change="checkItem(item.checkedData, index)"
>
<el-checkbox
v-for="(a, index) in item.children"
:label="a.value"
:key="index"
>{{ a.label }}</el-checkbox
>
</el-checkbox-group>
</div>
2、js部分
<script>
export default {
data() {
return {
data: [
{
isCheck: false,
isIndeterminate: true,
checkedData: [],
children: [
{
value: "11",
label: "分组1-1",
},
{
value: "12",
label: "分组1-2",
},
],
},
{
isCheck: false,
isIndeterminate: true,
checkedData: [],
children: [
{
value: "21",
label: "分组2-1",
},
{
value: "22",
label: "分组2-2",
},
{
value: "23",
label: "分组2-3",
},
{
value: "24",
label: "分组2-4",
},
],
},
],
};
},
methods: {
checkItem(val, index) {
let checkedCount = val.length;
this.data[index].isCheck =
checkedCount === this.data[index].children.length;
this.data[index].isIndeterminate =
checkedCount > 0 && checkedCount < this.data[index].children.length;
},
checkTitle(val, index) {
let arr = [];
const re = this.data[index].children;
//全选
if (val) {
for (let i = 0; i < re.length; i++) {
arr[i] = re[i]["value"];
}
}
this.data[index].checkedData = arr;
this.data[index].isIndeterminate = false;
},
},
};
</script>
效果图:
总结:
- indeterminate属性 表示 checkbox 的不确定状态 (小横线样式)
- 此代码中为mock数据,真实场景中,首先拿到接口返回数据,之后加工成前端想要的数据结构 (类似代码中data的数据格式),可通过for循环、map遍历、reduce等方式
- 在@change事件中写内部逻辑,最终实现功能