动态路由

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 路由递归处理
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);
}
};

路由守卫

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 路由守卫
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获取路由信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 路由递归处理
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" });
}
};