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

@@ -347,32 +347,62 @@ async function loadMenuList() {
// 将扁平数据转换为树形结构
function buildTree(flatData: SysMenu[]): SysMenu[] {
if (!flatData || flatData.length === 0) {
return [];
}
const tree: SysMenu[] = [];
const map: Record<string, SysMenu> = {};
const map = new Map<string, SysMenu>();
const maxDepth = flatData.length; // 最多遍历len层
// 创建映射表
// 初始化所有节点
flatData.forEach(item => {
if (item.menuID) {
map[item.menuID] = { ...item, children: [] };
map.set(item.menuID, { ...item, children: [] });
}
});
// 构建树结构
flatData.forEach(item => {
if (item.menuID) {
const node = map[item.menuID];
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.menuID) return;
const node = map.get(item.menuID);
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: SysMenu[]) {
@@ -389,6 +419,19 @@ function buildTree(flatData: SysMenu[]): SysMenu[] {
return tree;
}
// 检查节点是否已经在树中
function isNodeInTree(node: SysMenu, tree: SysMenu[]): boolean {
for (const treeNode of tree) {
if (treeNode.menuID === node.menuID) {
return true;
}
if (treeNode.children && isNodeInTree(node, treeNode.children)) {
return true;
}
}
return false;
}
// 新增菜单
function handleAdd() {
isEdit.value = false;