41 lines
1.0 KiB
TypeScript
41 lines
1.0 KiB
TypeScript
|
|
import { createRouter, createWebHistory } from 'vue-router';
|
||
|
|
import { routes } from './routes';
|
||
|
|
import { auth } from '@/hooks/useAuth';
|
||
|
|
|
||
|
|
const router = createRouter({
|
||
|
|
history: createWebHistory(import.meta.env.VITE_BASE_URL || '/'),
|
||
|
|
routes,
|
||
|
|
scrollBehavior: () => ({ left: 0, top: 0 }),
|
||
|
|
});
|
||
|
|
|
||
|
|
// 路由守卫:登录鉴权 + 页面标题
|
||
|
|
router.beforeEach((to, _from, next) => {
|
||
|
|
const isLoggedIn = auth.isLoggedIn();
|
||
|
|
|
||
|
|
// 设置页面标题
|
||
|
|
const appTitle = import.meta.env.VITE_APP_TITLE || 'CPMS 运营平台';
|
||
|
|
document.title = to.meta.title ? `${to.meta.title} - ${appTitle}` : appTitle;
|
||
|
|
|
||
|
|
// 如果访问的是登录页
|
||
|
|
if (to.path === '/login') {
|
||
|
|
if (isLoggedIn) {
|
||
|
|
// 已登录则重定向到首页
|
||
|
|
next('/dashboard');
|
||
|
|
} else {
|
||
|
|
// 未登录则允许访问登录页
|
||
|
|
next();
|
||
|
|
}
|
||
|
|
} else {
|
||
|
|
// 访问其他页面
|
||
|
|
if (isLoggedIn) {
|
||
|
|
// 已登录则允许访问
|
||
|
|
next();
|
||
|
|
} else {
|
||
|
|
// 未登录则重定向到登录页
|
||
|
|
next('/login');
|
||
|
|
}
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
export default router;
|