feat: 流式布局点击一级菜单定位到子路由

This commit is contained in:
2025-10-20 14:05:12 +08:00
parent 5163e4dee8
commit 1e5ea1879b
5 changed files with 138 additions and 178 deletions

69
src/utils/menuUtils.tsx Normal file
View File

@@ -0,0 +1,69 @@
import { Navigate } from '@umijs/max';
import { Spin } from 'antd';
import React from 'react';
export const loopMenuItem = (menus: any[], pId: number | string): any[] => {
// console.log(menus, "menus");
return menus.flatMap((item) => {
let Component: React.ComponentType<any> | null = null;
if (item.component && item.component.length > 0) {
// 防止配置了路由,但本地暂未添加对应的页面,产生的错误
Component = React.lazy(() => {
const importComponent = () => import(`@/pages/${item.component}`);
const import404 = () => import('@/pages/404');
return importComponent().catch(import404);
});
}
if (item.children && item.children.length > 0) {
return [
{
path: item.path,
name: item.name,
// icon: item.icon,
id: item.id,
parentId: pId,
children: [
{
path: item.path,
element: (
<Navigate
to={getFirstLeafPath(item.children, item.path)}
replace
/>
),
},
...loopMenuItem(item.children, item.menuID),
],
},
];
} else {
return [
{
path: item.path,
name: item.name,
// icon: item.icon,
id: item.menuID,
parentId: pId,
element: (
<React.Suspense
fallback={<Spin style={{ width: '100%', height: '100%' }} />}
>
{Component && <Component />}
</React.Suspense>
),
children: [], // 添加缺失的 children 属性
},
];
}
});
};
function getFirstLeafPath(menus: any[], parentPath: string): string {
const firstMenu = menus[0];
const currentPath = `${parentPath}/${firstMenu.path}`;
if (firstMenu.children && firstMenu.children.length > 0) {
return getFirstLeafPath(firstMenu.children, currentPath);
} else {
return currentPath;
}
}