import { nextTick } from 'vue'; import { RouteRecordRaw } from 'vue-router'; import pinia from '/@/stores/index'; import { useUserInfo } from '/@/stores/userInfo'; import { useRequestOldRoutes } from '/@/stores/requestOldRoutes'; import { Session } from '/@/utils/storage'; import { NextLoading } from '/@/utils/loading'; import { dynamicRoutes, notFoundAndNoPower } from '/@/router/route'; import { formatTwoStageRoutes, formatFlatteningRoutes, router } from '/@/router/index'; import { useRoutesList } from '/@/stores/routesList'; import { useTagsViewRoutes } from '/@/stores/tagsViewRoutes'; import { getAPI } from '/@/utils/axios-utils'; import { SysMenuApi } from '/@/api-services/api'; import { augmentAllowedPathsForAidopHomepage, patchAidopMenuTitles } from '/@/utils/aidopMenuDisplay'; // import { ElMessage } from 'element-plus'; // 后端控制路由 /** * 获取目录下的 .vue、.tsx 全部文件 * @method import.meta.glob * @link 参考:https://cn.vitejs.dev/guide/features.html#json */ const layouModules: any = import.meta.glob('../layout/routerView/*.{vue,tsx}'); const viewsModules: any = import.meta.glob('../views/**/*.{vue,tsx}'); const dynamicViewsModules: Record = Object.assign({}, { ...layouModules }, { ...viewsModules }); const DEFAULT_HOME_REDIRECT = '/dashboard/home'; function normalizeMenuPath(p: string | undefined | null): string { if (p == null || typeof p !== 'string') return ''; const t = p.trim(); if (!t) return ''; return t.startsWith('/') ? t : `/${t}`; } function collectMenuPathsFromTree(menus: any[] | undefined, acc: Set): void { for (const m of menus || []) { const np = normalizeMenuPath(m?.path); if (np) acc.add(np); if (m?.children?.length) collectMenuPathsFromTree(m.children, acc); } } /** 后端 MenuTypeEnum:2=菜单(可对应页面路由),排除目录与按钮 */ function pickFirstRoutableMenuPath(menus: any[] | undefined): string { for (const m of menus || []) { const t = Number(m?.type); if (t === 2) { const np = normalizeMenuPath(m?.path); if (np) return np; } const sub = pickFirstRoutableMenuPath(m?.children); if (sub) return sub; } return ''; } /** * 个性化首页仅当落在当前用户菜单 path 中时才作为根重定向; * 回退为「当前用户菜单树里第一个页面菜单」而非写死 /dashboard/home,避免受限角色 404。 */ function resolveHomeRedirect(menuTree: any[]): string { const fallback = pickFirstRoutableMenuPath(menuTree) || DEFAULT_HOME_REDIRECT; let hpRaw: string | undefined; try { hpRaw = Session.get('homepage') as string; } catch { hpRaw = undefined; } const hp = normalizeMenuPath(hpRaw); if (!hp) return fallback; const allowed = new Set(); collectMenuPathsFromTree(menuTree, allowed); augmentAllowedPathsForAidopHomepage(menuTree, allowed); if (allowed.has(hp)) return hp; const noTrail = hp.replace(/\/$/, '') || '/'; if (allowed.has(noTrail)) return noTrail; return fallback; } /** addRoute 之后:若根 redirect 仍无法匹配(组件解析失败等),再回退到可解析路径 */ async function clampRootRedirectAfterAddRoute(menuTree: any[]): Promise { await nextTick(); let target = normalizeMenuPath(dynamicRoutes[0].redirect as string) || DEFAULT_HOME_REDIRECT; const trySet = (p: string) => { const np = normalizeMenuPath(p); if (!np) return false; const { matched } = router.resolve(np); if (!matched.length) return false; dynamicRoutes[0].redirect = np; return true; }; if (trySet(target)) return; const fromMenu = pickFirstRoutableMenuPath(menuTree); if (fromMenu && trySet(fromMenu)) return; const walk = (nodes: any[] | undefined): string => { for (const n of nodes || []) { if (n.component === false) continue; const p = normalizeMenuPath(n.path); if (p && p !== '/' && n.component) { if (router.resolve(p).matched.length) return p; } const sub = walk(n.children); if (sub) return sub; } return ''; }; const fromCfg = walk(dynamicRoutes[0].children as any[]); if (fromCfg && trySet(fromCfg)) return; trySet(DEFAULT_HOME_REDIRECT); } /** * 后端控制路由:初始化方法,防止刷新时路由丢失 * @method NextLoading 界面 loading 动画开始执行 * @method useUserInfo().setUserInfos() 触发初始化用户信息 pinia * @method useRequestOldRoutes().setRequestOldRoutes() 存储接口原始路由(未处理component),根据需求选择使用 * @method setAddRoute 添加动态路由 * @method setFilterMenuAndCacheTagsViewRoutes 设置路由到 pinia routesList 中(已处理成多级嵌套路由)及缓存多级嵌套数组处理后的一维数组 */ export async function initBackEndControlRoutes() { // 界面 loading 动画开始执行 if (window.nextLoading === undefined) NextLoading.start(); // 无 token 停止执行下一步 if (!Session.get('token')) return false; // 触发初始化用户信息 pinia // https://gitee.com/lyt-top/vue-next-admin/issues/I5F1HP await useUserInfo().setUserInfos(); await useUserInfo().setConstList(); await useUserInfo().setDictList(); // 获取路由菜单数据 const res = await getBackEndControlRoutes(); // 无登录权限时,添加判断 // https://gitee.com/lyt-top/vue-next-admin/issues/I64HVO if (res == undefined || res.length <= 0) return Promise.resolve(true); // Ai-DOP:统一一级目录侧栏文案(与种子 S0–S9 一致,并兼容旧 aidopDirM01–M10) patchAidopMenuTitles(res as any[]); // 存储接口原始路由(未处理component),根据需求选择使用 useRequestOldRoutes().setRequestOldRoutes(res as string[]); // 处理路由(component),替换 dynamicRoutes(/@/router/route)第一个顶级 children 的路由 dynamicRoutes[0].children = await backEndComponent(res); dynamicRoutes[0].redirect = resolveHomeRedirect(res as any[]); // 添加动态路由 await setAddRoute(); await clampRootRedirectAfterAddRoute(res as any[]); // 设置路由到 pinia routesList 中(已处理成多级嵌套路由)及缓存多级嵌套数组处理后的一维数组 setFilterMenuAndCacheTagsViewRoutes(); } /** * 设置路由到 pinia routesList 中(已处理成多级嵌套路由)及缓存多级嵌套数组处理后的一维数组 * @description 用于左侧菜单、横向菜单的显示 * @description 用于 tagsView、菜单搜索中:未过滤隐藏的(isHide) */ export async function setFilterMenuAndCacheTagsViewRoutes() { const storesRoutesList = useRoutesList(pinia); storesRoutesList.setRoutesList(dynamicRoutes[0].children as any); setCacheTagsViewRoutes(); } /** * 缓存多级嵌套数组处理后的一维数组 * @description 用于 tagsView、菜单搜索中:未过滤隐藏的(isHide) */ export function setCacheTagsViewRoutes() { const storesTagsView = useTagsViewRoutes(pinia); storesTagsView.setTagsViewRoutes(formatTwoStageRoutes(formatFlatteningRoutes(dynamicRoutes))[0].children); } /** * 处理路由格式及添加捕获所有路由或 404 Not found 路由 * @description 替换 dynamicRoutes(/@/router/route)第一个顶级 children 的路由 * @returns 返回替换后的路由数组 */ export function setFilterRouteEnd() { let filterRouteEnd: any = formatTwoStageRoutes(formatFlatteningRoutes(dynamicRoutes)); // notFoundAndNoPower 防止 404、401 不在 layout 布局中,不设置的话,404、401 界面将全屏显示 // 关联问题 No match found for location with path 'xxx' filterRouteEnd[0].children = [...filterRouteEnd[0].children, ...notFoundAndNoPower]; return filterRouteEnd; } /** * 添加动态路由 * @method router.addRoute * @description 此处循环为 dynamicRoutes(/@/router/route)第一个顶级 children 的路由一维数组,非多级嵌套 * @link 参考:https://next.router.vuejs.org/zh/api/#addroute */ export async function setAddRoute() { await setFilterRouteEnd().forEach((route: RouteRecordRaw) => { router.addRoute(route); }); } /** * 请求后端路由菜单接口 * @description isRequestRoutes 为 true,则开启后端控制路由 * @returns 返回后端路由菜单数据 */ export async function getBackEndControlRoutes() { var res = await getAPI(SysMenuApi).apiSysMenuLoginMenuTreeGet(); // if (res.data.result == undefined || res.data.result.length < 1) { // ElMessage.error('没有任何菜单权限,请联系管理员!'); // setTimeout(() => { // Session.removeToken(); // window.location.reload(); // }, 3000); // } return res.data.result; } /** * 重新请求后端路由菜单接口 * @description 用于菜单管理界面刷新菜单(未进行测试) * @description 路径:/src/views/system/menu/component/addMenu.vue */ export async function setBackEndControlRefreshRoutes() { await getBackEndControlRoutes(); } /** * 后端路由 component 转换 * @param routes 后端返回的路由表数组 * @returns 返回处理成函数后的 component */ export function backEndComponent(routes: any) { if (!routes) return; return routes.map((item: any) => { if (!item.path) item.path = ''; // 防止后端返回的路由没有path属性,导致路由报错 if (item.component) item.component = dynamicImport(dynamicViewsModules, item.component as string); item.children && backEndComponent(item.children); return item; }); } /** * 后端路由 component 转换函数 * @param dynamicViewsModules 获取目录下的 .vue、.tsx 全部文件 * @param component 当前要处理项 component * @returns 返回处理成函数后的 component */ export function dynamicImport(dynamicViewsModules: Record, component: string) { if (component == null || component === '') return; const compTrim = String(component).trim(); // 后端目录菜单 component 为「Layout」,实际文件在 layout/routerView/parent.vue(小写),不能仅靠 startsWith 匹配 if (/^layout$/i.test(compTrim)) { const keys = Object.keys(dynamicViewsModules); const layoutKey = keys.find((key) => key.replace(/\\/g, '/').includes('/layout/routerView/parent.')); if (layoutKey) return dynamicViewsModules[layoutKey]; } const keys = Object.keys(dynamicViewsModules); const matchKeys = keys.filter((key) => { const k = key.replace(/..\/views|../, ''); return k.startsWith(`${component}`) || k.startsWith(`/${component}`); }); if (matchKeys?.length === 1) { const matchKey = matchKeys[0]; return dynamicViewsModules[matchKey]; } if (matchKeys?.length > 1) { return false; } }