使用element ui 表格中的树形结构点击全选时,子级并无选中状态
解决示例:
1.在table中加入 @select-all="handleSelectAll"方法,当用户手动勾选全选 Checkbox 时触发的事件
<el-table
ref="table"
v-bind="tableProps"
@select-all="handleSelectAll"
>
...
</el-table>
2.在handleSelectAll
方法中,使用toggleRowSelection
方法切换行的选中状态。
handleSelectAll(selection) {
// 获取当前表格的所有行
const fullData = this.$refs.table.store.states.data;
// 如果当前选中的行数为0,则取消全选
if (selection.length === 0) {
this.$refs.table.store.states.selection = [];
return;
}
// 遍历所有的行数据,找出子节点并添加到选项中
fullData.forEach(item => {
const children = item.children || [];
children.forEach(child => {
if (selection.includes(item)) {
this.$refs.table.toggleRowSelection(child, true);
} else {
this.$refs.table.toggleRowSelection(child, false);
}
});
});
}
在修改后的handleSelectAll
方法中,添加了一个判断语句。如果selection
数组中包含了父节点,就将其所有子节点选中;如果不包含父节点,就将其所有子节点取消选中。