feat: 架构调整
This commit is contained in:
+20
-28
@@ -1,40 +1,32 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router';
|
||||
import { routes } from './routes';
|
||||
import { auth } from '@/hooks/useAuth';
|
||||
import { constantRoutes } from './routes';
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(import.meta.env.VITE_BASE_URL || '/'),
|
||||
routes,
|
||||
routes: constantRoutes,
|
||||
scrollBehavior: () => ({ left: 0, top: 0 }),
|
||||
});
|
||||
|
||||
// 路由守卫:登录鉴权 + 页面标题
|
||||
router.beforeEach((to, _from, next) => {
|
||||
const isLoggedIn = auth.isLoggedIn();
|
||||
/**
|
||||
* 路由白名单:不需要登录即可访问的路径
|
||||
*/
|
||||
const WHITE_LIST = ['/login', '/404'];
|
||||
|
||||
// 设置页面标题
|
||||
const appTitle = import.meta.env.VITE_APP_TITLE || 'CPMS 运营平台';
|
||||
document.title = to.meta.title ? `${to.meta.title} - ${appTitle}` : appTitle;
|
||||
/**
|
||||
* 重置路由:清除动态添加的子路由,恢复到只包含静态路由的状态
|
||||
* 用于退出登录时清理
|
||||
*/
|
||||
export function resetRouter() {
|
||||
const currentRoutes = router.getRoutes();
|
||||
const protectedNames = new Set(['Login', 'BasicLayout', 'NotFound']);
|
||||
|
||||
// 如果访问的是登录页
|
||||
if (to.path === '/login') {
|
||||
if (isLoggedIn) {
|
||||
// 已登录则重定向到首页
|
||||
next('/dashboard');
|
||||
} else {
|
||||
// 未登录则允许访问登录页
|
||||
next();
|
||||
currentRoutes.forEach((route) => {
|
||||
// 保留静态路由(Login, BasicLayout, NotFound),移除动态添加的子路由
|
||||
if (!protectedNames.has(route.name as string)) {
|
||||
router.removeRoute(route.name!);
|
||||
}
|
||||
} else {
|
||||
// 访问其他页面
|
||||
if (isLoggedIn) {
|
||||
// 已登录则允许访问
|
||||
next();
|
||||
} else {
|
||||
// 未登录则重定向到登录页
|
||||
next('/login');
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export default router;
|
||||
export { WHITE_LIST };
|
||||
|
||||
Reference in New Issue
Block a user