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

View File

@@ -19,6 +19,8 @@ import '@ant-design/v5-patch-for-react-19';
import { useDictStore } from '@/hooks/stores/dict';
import { getAccessToken, getTenantId } from '@/utils/auth';
import { CACHE_KEY, useCache } from './hooks/web/useCache';
import type { MenuVO } from './services/system/menu';
import { loopMenuItem } from './utils/menuUtils';
const isDev = process.env.NODE_ENV === 'development';
const isDevOrTest = isDev || process.env.CI;
@@ -26,6 +28,8 @@ const loginPath = '/user/login';
// 全局存储菜单数据和路由映射
const dynamicRoutesAdded = false;
// 标记是否已添加动态路由
/**
* @see https://umijs.org/docs/api/runtime-config#getinitialstate
* */
@@ -33,6 +37,7 @@ export async function getInitialState(): Promise<{
settings?: Partial<LayoutSettings>;
currentUser?: UserInfoVO;
loading?: boolean;
menus?: MenuVO[];
fetchUserInfo?: () => Promise<UserInfoVO | undefined>;
}> {
const { wsCache } = useCache();
@@ -70,12 +75,14 @@ export async function getInitialState(): Promise<{
) {
const currentUser = wsCache.get(CACHE_KEY.USER);
if (getAccessToken() && !currentUser) {
fetchUserInfo();
await fetchUserInfo();
}
const menus = wsCache.get(CACHE_KEY.ROLE_ROUTERS);
console.log(111);
return {
fetchUserInfo,
currentUser,
menus,
settings: defaultSettings as Partial<LayoutSettings>,
};
}
@@ -227,87 +234,36 @@ export const request: RequestConfig = {
return searchParams.toString();
},
};
// umi 4 使用 modifyRoutes
export function patchClientRoutes({ routes }: { routes: any }) {
// Umi 4 支持异步的 patchClientRoutes
export async function patchClientRoutes({ routes }: any) {
const { wsCache } = useCache();
const globalMenus = wsCache.get(CACHE_KEY.ROLE_ROUTERS);
// 先尝试从缓存获取
let menus = wsCache.get(CACHE_KEY.ROLE_ROUTERS);
// 如果缓存没有,且有 token则获取
if (!menus && getAccessToken()) {
try {
const data = await getInfo();
wsCache.set(CACHE_KEY.USER, data);
wsCache.set(CACHE_KEY.ROLE_ROUTERS, data.menus);
menus = data.menus;
} catch (error) {
console.error('获取菜单失败:', error);
return;
}
}
if (!menus || menus.length === 0) {
return;
}
const routerIndex = routes.findIndex((item: any) => item.path === '/');
const parentId = routes[routerIndex].id;
if (globalMenus) {
routes[routerIndex].routes.push(...loopMenuItem(globalMenus, parentId));
if (menus) {
const r = loopMenuItem(menus, parentId);
console.log(r, routes);
routes[routerIndex].routes.push(...r);
}
}
const loopMenuItem = (menus: any[], pId: number | string): any[] => {
return menus.flatMap((item) => {
let Component: React.ComponentType<any> | null = null;
// console.log(findFirstLeafRoute(item), 'item');
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.url,
element: <Navigate to={item.children[0].url} replace />,
},
...loopMenuItem(item.children, item.menuID),
],
},
];
} else {
// console.log(findFirstLeafRoute(newItem));
return [
{
path: item.path,
name: item.name,
// icon: item.icon,
id: item.menuID,
parentId: pId,
redirect: '/system/tenant/list',
element: (
<React.Suspense
fallback={<Spin style={{ width: '100%', height: '100%' }} />}
>
{Component && <Component />}
</React.Suspense>
),
children: [], // 添加缺失的 children 属性
},
];
}
});
};
const _findFirstLeafRoute = (menuItem: any, parent = '/'): string | null => {
// 如果没有子菜单,返回当前路径
if (!menuItem.children || menuItem.children.length === 0) {
return parent + menuItem.path;
}
// 递归查找第一个叶子节点
for (const child of menuItem.children) {
// const leafRoute = findFirstLeafRoute(child, menuItem.path + "/");
const leafRoute = _findFirstLeafRoute(child, `${menuItem.path}/`);
if (leafRoute) {
return leafRoute;
}
}
return null;
};