初始化基础框架
This commit is contained in:
+51
-2
@@ -1,8 +1,57 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import { useUserStore } from '@/stores/modules/user'
|
||||
import Layout from '@/layouts/index.vue'
|
||||
|
||||
const routes = [
|
||||
{
|
||||
path: '/login',
|
||||
name: 'Login',
|
||||
component: () => import('@/pages/login/index.vue'),
|
||||
meta: { requiresAuth: false },
|
||||
},
|
||||
{
|
||||
path: '/',
|
||||
name: 'Dashboard',
|
||||
component: Layout,
|
||||
redirect: '/home',
|
||||
meta: { requiresAuth: true },
|
||||
children: [
|
||||
{
|
||||
path: '/home',
|
||||
name: 'Home',
|
||||
component: () => import('@/pages/home/Dashboard.vue'),
|
||||
meta: { requiresAuth: true },
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(import.meta.env.BASE_URL),
|
||||
routes: [],
|
||||
history: createWebHistory(import.meta.env.BASE_URL),
|
||||
routes: routes,
|
||||
})
|
||||
|
||||
// 路由拦截器 - 全局前置守卫
|
||||
router.beforeEach((to, from, next) => {
|
||||
const userStore = useUserStore()
|
||||
const isLoggedIn = userStore.isLoggedIn()
|
||||
|
||||
// 检查路由是否需要认证
|
||||
const requiresAuth = to.matched.some((record) => record.meta.requiresAuth !== false)
|
||||
|
||||
if (requiresAuth && !isLoggedIn) {
|
||||
// 需要认证但未登录,重定向到登录页
|
||||
next({
|
||||
path: '/login',
|
||||
query: { redirect: to.fullPath }, // 保存目标路径,登录后可以跳转回去
|
||||
})
|
||||
} else if (to.path === '/login' && isLoggedIn) {
|
||||
// 已登录但访问登录页,重定向到首页
|
||||
next({ path: '/' })
|
||||
} else {
|
||||
// 其他情况正常跳转
|
||||
next()
|
||||
}
|
||||
})
|
||||
|
||||
export default router
|
||||
|
||||
Reference in New Issue
Block a user