首页 > 教程
Vue3 + Vite + Vue Router 4后端返回路由配置动态路由权限管理
- 2025-04-07
- 1201 ℃
动态路由
// 路由递归处理
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);
}
};路由守卫
// 路由守卫
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 获取路由信息
// 路由递归处理
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" });
}
};相关内容
大学可以不用买学校订的教材
有人情味的Hume AI 会...
如何使用php与数据库进行交互
什么是深网?有危险吗?...
微信提现免手续费
微信的尊老爱幼模式,关...
什么是闰秒?这个困扰我5...
批量重命名文件,怎样快...
-
刷视频就能学技能知识!这个 神仙APP 我真的相见恨晚
2026-07-07 607
-
Deepseek 高效使用指南,1分钟学会
2025-04-30 1366
-
人人都是增长黑客
2024-05-29 1569
-
去美国必备口语推荐
2025-03-03 1233
-
Wireshark - 网络抓包工具截取并分析各种网络数据包
2025-06-16 1250
-
常用正则表达式
2021-05-06 831
-
微信的8个实用功能,隐藏技巧
2024-02-19 971
-
通过 SWOT 分析法,看美团优选的先天优势
2024-05-29 2897
-
微信怎么看好友是否把你删除?免打扰检测方法
2021-07-16 3181
-
app申请支付宝移动支付
2024-05-13 1648
文章评论 (0)
- 这篇文章还没有收到评论,赶紧来抢沙发吧~


进入有缘空间
点击分享文章