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 事件中写外部逻辑,最终实现性能