动态路由12345678910111213141516171819202122232425262728293031323334353637// 路由递归处理const AllRouter = import.meta.glob("@/views/**/*.vue");interface RouterItem { path: string; name: string; component: () => any; children?: RouterItem[]; meta: { title: string; icon: string; };}const routerFormat = (routerList: any): RouterItem[] => { if (!routerList || !Array.isArray(routerList)) return []; return routerList.map((item: any) => { return { ...item, component: AllRouter[`/src/views/${item["component"]}`], children: routerFormat(item["children"]), }; });};// 动态路由挂载const addDynamicRoutes = ( layoutRoute: RouteRecordRaw | undefined, page: RouteLocationNormalizedLoaded,) => { const newRouteStr = localStorage.getItem("routerList"); if (layoutRoute && newRouteStr && layoutRoute.children!.length < 1) { const newRouteArr = routerFormat( JSON.parse(newRouteStr) as RouteRecordRaw[], ); layoutRoute.children = newRouteArr; router.addRoute(layoutRoute); router.push(page); }};路由守卫123456789101112131415// 路由守卫router.beforeEach(async (to, from, next) => { // 每次请求判断动态路由是否挂载 const layoutRoute: RouteRecordRaw | undefined = router.options.routes.find( (route) => route.name === "Layout", ); addDynamicRoutes(layoutRoute, to); // 路由拦截规则 const TOKEN_STATIC: string | null = localStorage.getItem("session"); if (to.path === "/login" && TOKEN_STATIC) { next("/Layout"); } else { !TOKEN_STATIC && to.path !== "/login" ? next("/login") : next(); }});Login获取路由信息123456789101112131415161718192021222324252627// 路由递归处理const routerFormat = (routerList: any[]): any[] => { if (!routerList) return []; return routerList.map((item: any) => { return { path: item["url"], name: item["title"], component: item["component"], children: routerFormat(item["children"]), meta: { title: item["title"], icon: item["ico"], }, }; });};// 获取用户信息const getUserInfoFn = async (session: any) => { localStorage.setItem("session", session); const res = await getUserInfo(); if (res.code == 0) { const routerList = routerFormat(res.data.router_list); localStorage.setItem("userInfo", JSON.stringify(res.data.user_info)); localStorage.setItem("routerList", JSON.stringify(routerList)); router.push({ name: "Layout" }); }};