kindergarten_java/reading-platform-frontend/src/router/index.ts

66 lines
1.7 KiB
TypeScript
Raw Normal View History

/**
*
*
* 使 unplugin-vue-router
*
*/
import { createRouter, createWebHistory } from 'vue-router';
import { message } from 'ant-design-vue';
// 尝试导入自动生成的路由,如果失败则使用传统路由
let routes: any;
try {
// @ts-ignore - unplugin-vue-router 生成的虚拟模块
const autoRoutes = await import('vue-router/auto-routes');
routes = autoRoutes.routes;
} catch (e) {
console.warn('Auto-routes not available, falling back to manual routes');
// 如果自动路由不可用,导入传统路由
const manualRoutes = await import('./manual-routes');
routes = manualRoutes.default;
}
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes,
});
// 路由守卫
router.beforeEach((to, _from, next) => {
const token = localStorage.getItem('token');
const userRole = localStorage.getItem('role');
// 设置页面标题
if (to.meta.title) {
document.title = `${to.meta.title} - 幼儿阅读教学服务平台`;
}
// 需要认证但未登录
if (to.meta.requiresAuth !== false && !token && to.path !== '/login') {
message.warning('请先登录');
next('/login');
return;
}
// 已登录用户访问登录页,跳转到对应首页
if (to.path === '/login' && token) {
const defaultRoute = userRole ? `/${userRole}/dashboard` : '/admin/dashboard';
next(defaultRoute);
return;
}
// 角色权限检查
if (to.meta.role && userRole !== to.meta.role) {
message.error('没有权限访问该页面');
next(`/${userRole}/dashboard`);
return;
}
next();
});
export { router };
export default router;