43 lines
923 B
TypeScript
43 lines
923 B
TypeScript
|
|
import { createRouter, createWebHistory } from '@ionic/vue-router'
|
||
|
|
import HomePage from '@/pages/HomePage.vue'
|
||
|
|
import LoginPage from '@/pages/LoginPage.vue'
|
||
|
|
import { useAuthStore } from '@/stores/auth'
|
||
|
|
|
||
|
|
const routes = [
|
||
|
|
{
|
||
|
|
path: '/',
|
||
|
|
redirect: '/login'
|
||
|
|
},
|
||
|
|
{
|
||
|
|
path: '/login',
|
||
|
|
component: LoginPage
|
||
|
|
},
|
||
|
|
{
|
||
|
|
path: '/home',
|
||
|
|
component: HomePage,
|
||
|
|
meta: { requiresAuth: true }
|
||
|
|
}
|
||
|
|
]
|
||
|
|
|
||
|
|
const router = createRouter({
|
||
|
|
history: createWebHistory(),
|
||
|
|
routes
|
||
|
|
})
|
||
|
|
|
||
|
|
// 路由守卫
|
||
|
|
router.beforeEach((to, from, next) => {
|
||
|
|
const authStore = useAuthStore()
|
||
|
|
|
||
|
|
if (to.meta.requiresAuth && !authStore.state.value.isAuthenticated) {
|
||
|
|
// 需要认证但未登录,跳转到登录页
|
||
|
|
next('/login')
|
||
|
|
} else if (to.path === '/login' && authStore.state.value.isAuthenticated) {
|
||
|
|
// 已登录用户访问登录页,跳转到首页
|
||
|
|
next('/home')
|
||
|
|
} else {
|
||
|
|
next()
|
||
|
|
}
|
||
|
|
})
|
||
|
|
|
||
|
|
export default router
|