Vue+Pinia项目:已登录用户访问登录页的重定向导航守卫配置位置
实现已登录用户访问登录页自动重定向的解决方案
结合你的Pinia状态管理和Vue Router,只需在路由配置文件中添加全局导航守卫即可实现需求,同时需要完善Pinia的状态初始化逻辑,确保页面刷新后登录状态不丢失。
步骤1:完善Pinia的Auth Store状态同步
首先修改backend/src/store/auth.js,确保登录状态(isLoggedin)能正确同步:
import { defineStore } from 'pinia'; import axios from 'axios'; export const useAuthStore = defineStore("auth", { state: () => ({ authUser: null, authErros: [], authStatus: null, isLoggedin: false, }), getters: { user: (state) => state.authUser, errors: (state) => state.authErros, status: (state) => state.authStatus, loggedin: (state) => state.isLoggedin, }, actions: { async getToken() { await axios.get('/sanctum/csrf-cookie'); }, async getUser() { await this.getToken(); try{ const data = await axios.get('api/user'); this.authUser = data.data; this.isLoggedin = true; // 登录状态设为true } catch(error) { this.authUser = null; this.isLoggedin = false; // 未登录设为false } }, async handleLogin (data) { this.authErros = []; await this.getToken(); try{ await axios.post('/login', { email: data.email, password: data.password }); await this.getUser(); // 登录后同步用户状态 this.router.push("/dashboard"); } catch(error){ if(error.response.status === 422){ this.authErros = error.response.data.errors } } }, async handleRegister (data) { this.authErros = []; await this.getToken(); try{ await axios.post('/register', { name: data.name, email: data.email, password: data.password, password_confirmation: data.password_confirmation }); await this.getUser(); // 注册后同步用户状态 this.router.push("/dashboard"); } catch(error){ if(error.response.status === 422) { this.authErros = error.response.data.errors; } } }, async handleLogout () { try{ await axios.post('/logout'); } finally { this.authUser = null; this.isLoggedin = false; // 登出后重置状态 } }, // 其他action保持不变 async handleForgotPassword (email) { this.authErros = []; this.getToken(); try { const response = await axios.post('/forgot-password', { email: email }); this.authStatus = response.data.status; } catch (error) { if(error.response.status === 422) { this.authErros = error.response.data.errors; } } }, async handleResetPassword (resetData) { this.authErros = []; try { const response = await axios.post('/reset-password', resetData); this.authStatus = response.data.status; } catch (error) { if(error.response.status === 422) { this.authErros = error.response.data.errors; } } } } })
步骤2:在路由中添加全局导航守卫
修改backend/src/router/index.js,添加全局前置守卫,判断用户状态并处理重定向:
import { createRouter, createWebHistory } from 'vue-router' import { useAuthStore } from '../store/auth' // 导入Auth Store import Dashboard from '../views/Dashboard.vue' import Home from '../views/Home.vue' import Login from '../views/Login.vue' import RequestPassword from '../views/RequestPassword.vue' import ResetPassword from '../views/ResetPassword.vue' import Register from '../views/Register.vue' const routes = [ // 路由配置保持不变 { path: '/', name: 'home', component: Home }, { path: '/dashboard', name: 'dashboard', component: Dashboard }, { path: '/login', name: 'login', component: Login }, { path: '/forgot-password', name: 'requestPassword', component: RequestPassword, }, { path: '/password-reset/:token', name: 'resetPassword', component: ResetPassword, }, { path: '/register', name: 'register', component: Register }, ]; const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: routes, linkActiveClass: 'active' }) // 添加全局前置守卫 router.beforeEach(async (to, from, next) => { const authStore = useAuthStore() // 页面刷新时,先初始化用户状态 if (!authStore.authUser && authStore.isLoggedin === false) { await authStore.getUser() } // 定义不需要登录即可访问的页面 const publicAuthPages = ['/login', '/register', '/forgot-password'] // 处理带token的重置密码页面 const isResetPasswordPage = to.path.startsWith('/password-reset/') const isPublicPage = publicAuthPages.includes(to.path) || isResetPasswordPage // 已登录用户访问登录/注册等页面时,重定向到dashboard if (isPublicPage && authStore.isLoggedin) { next('/dashboard') } else { next() } }) export default router
步骤3:初始化用户状态(可选但推荐)
为了确保页面刷新后能立即获取登录状态,在App.vue中添加初始化逻辑:
<script setup> import { useAuthStore } from './store/auth' import { onMounted } from 'vue' const authStore = useAuthStore() onMounted(async () => { // 页面加载时同步用户状态 await authStore.getUser() }) </script>
这样配置后,已登录用户访问登录、注册、密码重置等页面时,会自动被重定向到Dashboard页面;未登录用户则可以正常访问这些页面。
内容的提问来源于stack exchange,提问作者clydekarnage
相关产品推荐
相关产品推荐

