element-plus Tree组件获取已勾选的子树

36 阅读1分钟

背景

element-plus组件有提供 getCheckedNodesgetCheckedKeys 函数, 用于获取已勾选的节点,但是,并没有函数用于获取已勾选的子树。

如果当前树是父子相关的(check-strictly为false,勾选的节点的父节点,也处于半勾选状态),要获取已勾选的子树,可以根据已勾选的节点,递归遍历树来实现。

思路

具体实现步骤如下:

  1. 建立一个集合,存放所有已勾选、半勾选的节点key。

  2. 对树进行前序遍历:

    2.1 从当前子树中过滤出已勾选、半勾选的节点。

    2.2 递归遍历已勾选、半勾选节点的子树,过滤出已勾选、半勾选的节点。

实现

实现代码如下:

 <el-tree ref="treeRef" node-key="id" :data="treeData"
      @check-change="changeFn"></el-tree>
import { ref, defineExpose } from 'vue';

const treeRef = ref();
const getSelectedSubTree = () => {
  const allCheckedKeys = treeRef.value.getCheckedKeys(); // 全选节点Key
  const halfCheckedKeys = treeRef.value.getHalfCheckedKeys(); // 半选节点Key
  // 合并 key,因为半选节点是构建子树结构所必需的
  const relevantKeys = [...new Set([...allCheckedKeys, ...halfCheckedKeys])];
  return handle(treeData, relevantKeys);
};

const handle = (nodes, relevantKeys) => {
  return nodes.filter(item => relevantKeys.has(item.id)).map(item => {
    return {
      ...item,
      children: item.children?.length ? handle(item.children, relevantKeys) : null
    }
  })
};

defineExpose({
  getSelectedSubTree
});

效果

20251207_164352_image.png