menu路由构建优化

This commit is contained in:
2025-10-15 17:54:40 +08:00
parent ab22fe1008
commit 5f76c539f4
4 changed files with 189 additions and 57 deletions

View File

@@ -271,32 +271,62 @@ async function loadDeptList() {
// 将扁平数据转换为树形结构
function buildTree(flatData: SysDept[]): SysDept[] {
if (!flatData || flatData.length === 0) {
return [];
}
const tree: SysDept[] = [];
const map: Record<string, SysDept> = {};
const map = new Map<string, SysDept>();
const maxDepth = flatData.length; // 最多遍历len层
// 创建映射表
// 初始化所有节点
flatData.forEach(item => {
if (item.deptID) {
map[item.deptID] = { ...item, children: [] };
map.set(item.deptID, { ...item, children: [] });
}
});
// 构建树结构
flatData.forEach(item => {
if (item.deptID) {
const node = map[item.deptID];
if (item.parentID && map[item.parentID]) {
// 有父节点添加到父节点的children中
if (!map[item.parentID].children) {
map[item.parentID].children = [];
}
map[item.parentID].children!.push(node);
} else {
// 没有父节点或父节点不存在,作为根节点
tree.push(node);
// 循环构建树结构最多遍历maxDepth次
for (let depth = 0; depth < maxDepth; depth++) {
let hasChanges = false;
flatData.forEach(item => {
if (!item.deptID) return;
const node = map.get(item.deptID);
if (!node) return;
// 如果节点已经在树中,跳过
if (isNodeInTree(node, tree)) {
return;
}
if (!item.parentID || item.parentID === '0' || item.parentID === '') {
// 根节点
if (!isNodeInTree(node, tree)) {
tree.push(node);
hasChanges = true;
}
} else {
// 查找父节点
const parent = map.get(item.parentID);
if (parent && isNodeInTree(parent, tree)) {
if (!parent.children) {
parent.children = [];
}
if (!parent.children.includes(node)) {
parent.children.push(node);
hasChanges = true;
}
}
}
});
// 如果没有变化,说明树构建完成
if (!hasChanges) {
break;
}
});
}
// 清理空的children数组
function cleanEmptyChildren(nodes: SysDept[]) {
@@ -313,6 +343,19 @@ function buildTree(flatData: SysDept[]): SysDept[] {
return tree;
}
// 检查节点是否已经在树中
function isNodeInTree(node: SysDept, tree: SysDept[]): boolean {
for (const treeNode of tree) {
if (treeNode.deptID === node.deptID) {
return true;
}
if (treeNode.children && isNodeInTree(node, treeNode.children)) {
return true;
}
}
return false;
}
// 新增部门
function handleAdd() {
isEdit.value = false;