仓库初始化+岗位相关页面
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
import type { RouteRecordRaw } from 'vue-router'
|
||||
import type { MenuItemRaw } from '@/api/menu'
|
||||
|
||||
/**
|
||||
* 组件映射表
|
||||
*
|
||||
* key = 后端返回的 component 字符串
|
||||
* value = 对应的懒加载组件
|
||||
*
|
||||
* 【新增页面时】在这里加一条映射即可,后端返回对应的 key 就能自动注册路由
|
||||
*/
|
||||
const componentMap: Record<string, () => Promise<any>> = {
|
||||
'Agent': () => import('@/views/Agent.vue'),
|
||||
'Profile': () => import('@/views/Profile.vue'),
|
||||
'Resume': () => import('@/views/Resume.vue'),
|
||||
}
|
||||
|
||||
/**
|
||||
* 把后端返回的菜单数据转换成 vue-router 能识别的 RouteRecordRaw
|
||||
*
|
||||
* 如果后端返回了一个 component 字符串在映射表里找不到,会跳过该条路由并打印警告
|
||||
*/
|
||||
export function buildDynamicRoutes(menus: MenuItemRaw[]): RouteRecordRaw[] {
|
||||
const routes: RouteRecordRaw[] = []
|
||||
|
||||
for (const item of menus) {
|
||||
const comp = componentMap[item.component]
|
||||
if (!comp) {
|
||||
console.warn(`[dynamicRoutes] 组件映射表中找不到 "${item.component}",已跳过`)
|
||||
continue
|
||||
}
|
||||
routes.push({
|
||||
path: item.path,
|
||||
name: item.name,
|
||||
component: comp,
|
||||
meta: { ...item.meta },
|
||||
})
|
||||
}
|
||||
|
||||
return routes
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import type { RouteRecordRaw } from 'vue-router'
|
||||
import store from '@/stores'
|
||||
|
||||
/**
|
||||
* 静态路由 — 不需要权限,应用启动就注册
|
||||
*/
|
||||
const staticRoutes: RouteRecordRaw[] = [
|
||||
{ path: '/', name: 'Home', component: () => import('@/views/Home.vue') },
|
||||
{ path: '/jobs', name: 'Jobs', component: () => import('@/views/Jobs.vue') },
|
||||
{
|
||||
path: '/resume/:id',
|
||||
name: 'ResumeDetail',
|
||||
component: () => import('@/views/ResumeDetail.vue'),
|
||||
meta: { requiresAuth: true },
|
||||
},
|
||||
{
|
||||
path: '/jobs/:id',
|
||||
name: 'JobDetail',
|
||||
component: () => import('@/views/JobDetail.vue'),
|
||||
},
|
||||
]
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
routes: staticRoutes,
|
||||
})
|
||||
|
||||
/**
|
||||
* 全局前置守卫 — 核心逻辑:
|
||||
*
|
||||
* 1. 动态路由未加载 → 先拉取并注册,再重新进入当前路由
|
||||
* 2. 需要鉴权的路由没有 token → 回首页
|
||||
* 3. 其他情况 → 直接放行
|
||||
*/
|
||||
router.beforeEach(async (to, _from, next) => {
|
||||
// 动态路由只需加载一次,与登录状态无关
|
||||
if (!store.state.routesLoaded) {
|
||||
try {
|
||||
await store.dispatch('loadDynamicRoutes', router)
|
||||
next({ ...to, replace: true })
|
||||
} catch (err) {
|
||||
console.error('[router] 加载动态路由失败', err)
|
||||
next({ name: 'Home' })
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 需要鉴权的路由,未登录则回首页
|
||||
if (to.meta?.requiresAuth && !store.state.isAuthenticated) {
|
||||
next({ name: 'Home' })
|
||||
return
|
||||
}
|
||||
|
||||
next()
|
||||
})
|
||||
|
||||
export default router
|
||||
Reference in New Issue
Block a user