el-table表格进行多选时仅能选中当前一行,对树状结构的多选来说不符合需求
下面要实现的是选中父节点,同时选中其下所有子节点:
表格中使用select方法(当用户手动勾选数据行的 Checkbox 时触发的事件)用于解决同时勾选所有子节点,row-click方法实现点击某一行进行勾选
<template>
<div class="treeTable"
<el-table ref="tree" :data="treeData" default-expand-all row-key="id"
@row-click="rowClick"
@select="handleSelection" >
<el-table-column type="selection" width="55" />
<el-table-column label="目录名称" prop="title" />
</el-table>
</div>
</template>
数据如下:
data() {
return {
treeData: [
{
id: '1765188101372870657', title: '目录1',
children: [
{
id: '1765188210793873409', title: '目录1-1',
children: [
{
id: '1765188330184736769', title: '目录1-1-1',
children: null,
},
{
id: '1765188397025165313', title: '目录1-1-2',
children: null,
},
],
},
],
},
{
id: '1765188457641246722', title: '目录2',
children: [
{
id: '1765188542143889410', title: '目录2-1',
children: null,
},
{
id: '1765188589640187905', title: '目录2-2',
children: [
{
id: '1765188652638633985', title: '目录2-2-1',
children: null,
},
],
},
],
},
],
}
}
运用选中递归方法checkRow实现勾选所有子节点:
methods: {
//选中递归
checkRow(data, bool) {
data.forEach((item) => {
this.$refs.tree.toggleRowSelection(item, bool);
if (item.children) {
this.checkRow(item.children, bool);
}
});
},
//选中菜单
handleSelection(select, row) {
if (!row.children) {
return false;
}
if (this.$refs.tree.selection.includes(row)) {
this.checkRow(row.children, true); // 调用选中递归方法
} else {
this.checkRow(row.children, false);
}
},
//点击表格回调
rowClick(row) {
if (!row.children) {
if (this.$refs.tree.selection.includes(row)) {
this.$refs.tree.toggleRowSelection(row, false);
} else {
this.$refs.tree.toggleRowSelection(row, true);
}
return;
}
if (this.$refs.tree.selection.includes(row)) {
this.$refs.tree.toggleRowSelection(row, false);
this.checkRow(row.children, false); // 调用选中递归方法
} else {
this.$refs.tree.toggleRowSelection(row, true);
this.checkRow(row.children, true);
}
},
}
以上是实现选中父节点同时选中其所有子节点的方法。