移除动态路由
将后端驱动的动态路由改为前端静态路由,适用于权限固定的内网系统。
改动点
| 文件 | 操作 |
|---|---|
src/router/guards/permission.ts | 删除动态路由生成逻辑 |
src/stores/permission.ts | generateRoutes 改为返回静态路由 |
src/router/index.ts | 把所有菜单路由写进 constantRoutes |
具体步骤
1. 移除守卫中的动态路由生成
src/router/guards/permission.ts 中删除以下动态路由生成逻辑:
typescript
// 删除以下逻辑
if (!permissionStore.isRouteGenerated) {
const dynamicRoutes = await permissionStore.generateRoutes();
dynamicRoutes.forEach((route) => router.addRoute(route));
return { ...to, replace: true };
}2. 简化路由生成
src/stores/permission.ts 的 generateRoutes 改为直接返回静态路由:
typescript
export const usePermissionStore = defineStore("permission", () => {
const routes = ref<RouteRecordRaw[]>([]);
function generateRoutes() {
routes.value = [...constantRoutes];
}
return { routes, generateRoutes };
});3. 配置静态路由
src/router/index.ts 中把菜单路由全部写入 constantRoutes:
typescript
export const constantRoutes: RouteRecordRaw[] = [
{
path: "/",
component: Layout,
redirect: "/dashboard",
children: [
{
path: "dashboard",
name: "Dashboard",
component: () => import("@/views/dashboard/index.vue"),
meta: { title: "dashboard", icon: "homepage", affix: true, keepAlive: true },
},
],
},
{
path: "/system",
component: Layout,
redirect: "/system/user",
meta: { title: "system", icon: "setting" },
children: [
{
path: "user",
name: "User",
component: () => import("@/views/system/user/index.vue"),
meta: { title: "用户管理", icon: "user" },
},
{
path: "role",
name: "Role",
component: () => import("@/views/system/role/index.vue"),
meta: { title: "角色管理", icon: "role" },
},
],
},
{
path: "/:pathMatch(.*)*",
component: () => import("@/views/error/404.vue"),
meta: { hidden: true },
},
];验证
pnpm run dev启动后直接访问/system/user能进入页面- 侧边栏菜单完整显示
- 按钮权限仍通过
v-hasPerm生效(详见权限控制)
