首页 > 教程
Vue3 + Vite + Vue Router 4后端返回路由配置动态路由权限管理
- 2025-04-07
- 1056 ℃
动态路由
// 路由递归处理
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" });
}
};相关内容
FastStone Capture电脑截屏工具
你真的知道怎么搜索网盘...
如果你也想做公众号挣钱
网站快照被劫持跳转另一...
支持上百个网站的漫画下...
phpMyAdmin导入超大数据...
摄影专业分享摄影技巧
固态硬盘必做的SSD优化,...
-
原生JS简易计算器
2025-04-07 1063
-
Coze 扣子 - 字节出品的超强 AI Bot 工具教程,免费无限白嫖 GPT4 方法
2024-04-07 2660
-
支持上百个网站的漫画下载神器
2025-04-27 960
-
3个DeepSeek隐藏玩法,99%的人都不知道
2025-04-30 956
-
你真的知道怎么搜索网盘资源吗
2025-03-10 1641
-
macOS Sierra 10.12 显示允许任何来源 – 解决身份不明的开发者程序安装
2024-08-06 1497
-
微信语音撤回不留痕迹
2021-08-07 1108
-
使用电脑一定要学会的20个小技巧
2024-02-19 806
-
知网文献免费下载、论文免费查重和去重的方法
2025-03-10 1275
-
2025年8款免费且好用的图片翻译工具
2025-03-04 1608
文章评论 (0)
- 这篇文章还没有收到评论,赶紧来抢沙发吧~


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