DeptTree.vue 1.98 KB
<template>
  <div class="m-4 mr-0 overflow-hidden bg-white">
    <BasicTree
      ref="treeRef"
      toolbar
      search
      treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
      :clickRowToExpand="false"
      :defaultExpandAll="true"
      :treeData="treeData"
      :fieldNames="{ key: 'selectedDeptId', title: 'name' }"
      @select="handleSelect"
    />
  </div>
</template>

<script lang="ts" setup>
  import { nextTick, onMounted, ref, unref } from 'vue';
  import { BasicTree, TreeActionType, TreeItem } from '@/components/Tree';

  import { Nullable } from '@vben/types';
  import { tableList, treeDataList } from './mock';

  defineOptions({ name: 'DeptTree' });

  const emit = defineEmits(['select']);

  const treeData = ref<TreeItem[]>([]);
  const treeRef = ref<Nullable<TreeActionType>>(null);

  // 合并数据的函数
  function mergeTreeDataWithTableList(treeDataList, tableList) {
    return treeDataList.map((treeNode) => {
      // 找到对应的tableList项,合并name属性
      const tableItem = tableList.find((item) => item.selectedDeptId === treeNode.selectedDeptId);
      if (tableItem) {
        treeNode.name = tableItem.name; // 将tableList中的name添加到treeNode
      }

      // 如果有子节点,递归处理
      if (treeNode.children && treeNode.children.length > 0) {
        treeNode.children = mergeTreeDataWithTableList(treeNode.children, tableList);
      }

      return treeNode;
    });
  }

  async function fetch() {
    // 合并树形数据和表格数据
    treeData.value = mergeTreeDataWithTableList(treeDataList, tableList);

    await nextTick(() => {
      getTree(treeRef).expandAll(true);
    });
  }

  function getTree(treeRef) {
    const tree = unref(treeRef);
    if (!tree) {
      throw new Error('tree is null!');
    }
    return tree;
  }

  function handleSelect(selectedDeptId) {
    emit('select', selectedDeptId[0]);
    console.log('selectedDeptId:', selectedDeptId);
  }

  onMounted(() => {
    fetch();
  });
</script>