1.最终效果
可以看到树结构中有部门,部门下的人员也需要显示。那么需要将人员和部门都当做子节点
2.数据分析
从后端返回数据来看,员工被统一放在一个数组中,并不是一个一个独立的子节点,所以这里封装一个递归方法来处理数据
//格式化树结构
const formatDepartTree = (node: any[]): any[] => {
const res: any[] = [];
if (!node) {//判空
return [];
}
for (const custNode of node) {
//定义组装数据后需要的常量
const title = custNode?.depart;
const empNames = custNode?.empNames;
const flag = 'dept';//标识子节点类型
const key = custNode?.deptId;
const value = custNode?.deptId;
const slots = { icon: 'dept' };//标识子节点插槽类型
//将员工抽出来当做子节点
if ('empNames' in custNode && custNode?.empNames) {
for (const emp of custNode.empNames) {
const title = emp?.empName;
const key = emp?.empId + Math.ceil(Math.random() * 10000);
const value = emp?.empId;
const flag = 'peo';
const slots = { icon: 'peo' };
children.unshift({ title: title, key: key, value: value, flag: flag, slots: slots });
}
}
res.push({ title, value, key, children, flag, slots, empNames });
}
//递归调用
const children: any[] = formatDepartTree(custNode.children);
return res;
};
调用函数之后的数据就可以直接给a-tree组件使用了
<a-tree show-icon :expanded-keys="expandedKeys" :auto-expand-parent="autoExpandParent" :tree-data="treeData" height="100" @expand="onExpand" @select="selectOne" @dragenter="onDragEnter" @drop="onDrop">
<template #dept>
<GoldTwoTone />
</template>
<template #peo>
<UserOutlined />
</template>
<template #title="{ title }">
<span v-if="title && title.indexOf(searchValue) > -1">
{{ title.substr(0, title.indexOf(searchValue)) }}
<span style="color: #f50">{{ searchValue }}</span>
{{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
</span>
<span v-else>{{ title }}</span>
</template>
</a-tree>
3.树结构数据优化
1.给树加上层级
2.加上parentId(用于拖拽时直接拿到子节点的父节点id)
//在格式化后的树中增加层级:'1','1-1','1-1-2'..
const formatTreeLevl = (data: any) => {
if (!data) return [];//判空
const find = (arr, parentId = '', parentLevl = '') => {
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i].children) && arr[i].children.length > 0) {
const resParentId: string = parentLevl ? `${parentLevl}-${i + 1}` : `${i + 1}`;
arr[i].idCode = resParentId;//层级
arr[i].parentId = parentId;//父级id
const last_parentId = arr[i].value;
//递归调用
find(arr[i].children, last_parentId, resParentId);
} else {
arr[i].parentId = parentId;
arr[i].idCode = parentLevl ? `${parentLevl}-${i + 1}` : i + 1;
}
}
};
const authDataCopy = data;
find(authDataCopy);
console.log(authDataCopy)
return authDataCopy;
};
处理后的数据