首页 > 教程
Vue3 + Vite + Vue Router 4后端返回路由配置动态路由权限管理
- 2025-04-07
- 1165 ℃
动态路由
// 路由递归处理
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" });
}
};相关内容
怎么复制网站(禁止鼠标右...
注册申请微信公众号(服...
鼠标拖拽移动DIV
网页上的视频怎么下载
为什么没有空间大,不限...
php批量去除文件bom代码
教你查询手机号绑定了哪...
Coze 扣子 - 字节出品...
-
PHP读本地文件指定某行内容
2025-04-07 1172
-
微信快速查看未读消息清理小红点
2025-06-22 1492
-
微信支付钱给错了怎么办?
2025-06-22 1467
-
语音转文字,文字转语音,两极互转
2025-03-10 1288
-
CSS动态渐变彩色文字代码
2025-04-07 1333
-
mysql数据库优化
2021-07-27 992
-
Duplicate Cleaner Pro 重复文件查找清理工具
2021-07-16 1388
-
微信最致命的查岗功能,查对象往祖坟上刨
2025-06-22 1476
-
人工智能:探索未知领域的科技之光
2024-04-24 1204
-
这些搜索方法可以助你事半功倍
2025-03-10 1494
文章评论 (0)
- 这篇文章还没有收到评论,赶紧来抢沙发吧~


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