feat(web): router with auth guard, AppShell, login + home views

This commit is contained in:
2026-04-29 10:02:45 +08:00
parent 3eb595cf5e
commit 9d93bcd24b
8 changed files with 181 additions and 4 deletions
+48
View File
@@ -0,0 +1,48 @@
import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { configure } from '@/api/client'
const routes: RouteRecordRaw[] = [
{
path: '/login',
name: 'login',
component: () => import('@/views/auth/LoginView.vue'),
meta: { layout: 'none' },
},
{
path: '/',
name: 'home',
component: () => import('@/views/HomeView.vue'),
meta: { layout: 'app', requiresAuth: true },
},
]
const router = createRouter({
history: createWebHistory(),
routes,
})
router.beforeEach((to) => {
const auth = useAuthStore()
if (to.meta.requiresAuth && !auth.isAuthenticated) {
return { name: 'login', query: { next: to.fullPath } }
}
if (to.name === 'login' && auth.isAuthenticated) {
return { name: 'home' }
}
return true
})
export default router
// 把 auth store 注入 api client(在 router 模块顶层晚于 pinia 安装可能未就绪,所以用懒访问)
export function bindAuthToApi() {
const auth = useAuthStore()
configure({
tokenProvider: () => auth.token,
onUnauthorized: () => {
auth.clearSession()
router.replace({ name: 'login' })
},
})
}