<el-table-column width="40" :render-header="headerRender">
<template slot-scope="scope">
<el-checkbox
v-model="scope.row.isSelected"
:disabled="scope.row.isDisabled"
@change="val => selectRow(val, scope.row)"
></el-checkbox>
</template>
</el-table-column>

private isSelectedAll = false;

headerRender(h: any) {
return h('el-checkbox', {
on: {
change: (val: any) => {
this.isSelectedAll = val;
this.selectAll();
},
},
});
}

selectAll() {
this.tableData.forEach(row => {
this.$set(row, 'isSelected', this.isSelectedAll);
row.children?.forEach((item: any) => {
this.$set(item, 'isSelected', this.isSelectedAll);
});
});
}

selectRow(val: boolean, row: any) {
// 点击的是父节点
if (row.children?.length) {
// 设置子节点全选/全不选
row.children.forEach((item: any) => {
if (!item.isDisabled) {
this.$set(item, 'isSelected', val);
}
});
} else {
let parentIndex = -1;
const parentRow = this.tableData.find((item: any, index) => {
if (row.packageName === item.packageName) {
parentIndex = index;
return true;
}
return false;
});
if (val && parentIndex >= 0) {
// 查找children内是否还有未勾选的 && isDisabled === false
const children = parentRow?.children?.find((item: any) => !item.isSelected && item.isDisabled === false);
if (!children) this.$set(this.tableData[parentIndex], 'isSelected', val);
} else {
this.$set(this.tableData[parentIndex], 'isSelected', val);
}
}
}

码字不易,觉得有帮助的小伙伴记得点个赞鼓励下~

Element 树表格自定义全选 Header_element

扫描上方二维码关注我的订阅号~