完美解决ElementUI中树形结构table勾选问题

发布于:2025-03-14 ⋅ 阅读:(21) ⋅ 点赞:(0)

完美解决ElementUI中树形结构table勾选问题

实现功能

1. 全选/取消全选,更新所有节点勾选状态
2. 勾选父/子节点,子/父节点状态和全选框状态更新

效果图

全选

在这里插入图片描述

取消全选

在这里插入图片描述

取消父节点

在这里插入图片描述

取消某个子节点

在这里插入图片描述

关键代码

这里是vue2写法,不管什么写法逻辑是一样滴!

<template>
  <el-table
    ref="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;

网站公告

今日签到

点亮在社区的每一天
去签到