完美解决ElementUI中树形结构table勾选问题
- 实现功能
- 效果图
- 全选
- 取消全选
- 取消父节点
- 取消某个子节点
- 关键代码
实现功能
1. 全选/取消全选,更新所有节点勾选状态
2. 勾选父/子节点,子/父节点状态和全选框状态更新
效果图
全选
取消全选
取消父节点
取消某个子节点
关键代码
这里是vue2写法,不管什么写法逻辑是一样滴!
<template><el-tableref="multipleTable"v-loading="loading"row-key="id":data="tableList":tree-props="{ children: 'children' }"@select-all="selectAll"@select="handleSelect"><el-table-column type="selection" width="55"> </el-table-column></el-table>
</template>
<script>
export default {methods: {// 递归设置子节点的勾选状态setChildrenSelection(children, selected) {if (!children || children.length === 0) return;children.forEach((child) => {this.$refs.multipleTable.toggleRowSelection(child, selected);this.setChildrenSelection(child.children, selected);});},// 更新父节点的勾选状态updateParentSelection(node) {if (!node || !node.pid) return; // 如果没有父节点,递归终止const parent = this.findNodeById(node.pid);if (!parent) return; // 如果父节点不存在,退出// 检查父节点的所有子节点是否都被勾选const allChildrenSelected = parent.children.every((child) =>this.$refs.multipleTable.selection.some((item) => item.id === child.id));// 根据子节点的勾选状态更新父节点的勾选状态this.$refs.multipleTable.toggleRowSelection(parent, allChildrenSelected);// 递归更新父节点的父节点this.updateParentSelection(parent);},// 根据 ID 查找节点findNodeById(id) {const stack = [...this.tableList];while (stack.length) {const node = stack.pop();if (node.id === id) return node;if (node.children && node.children.length) {stack.push(...node.children);}}return null;},// 勾选事件处理handleSelect(selection, row) {if (row.children && row.children.length) {// 如果当前节点有子节点,递归设置子节点的勾选状态const isCurrentSelected = selection.some((item) => item.id === row.id);this.setChildrenSelection(row.children, isCurrentSelected);}// 更新父节点的勾选状态this.updateParentSelection(row);},// 全选事件处理selectAll(selection) {this.tableList.forEach((row) => {const isRowSelected = selection.some((item) => item.id === row.id);this.$refs.multipleTable.toggleRowSelection(row, isRowSelected);// 递归设置子节点的勾选状态this.setChildrenSelection(row.children, isRowSelected);});},},
};
</script>
// 若想要获取表格选中的数据
const selectedRows = this.$refs.multipleTable.selection;