From d6f3cfe25c09d0b7d98a753b4580a07775734440 Mon Sep 17 00:00:00 2001 From: Leo <98382335+gaoziman@users.noreply.github.com> Date: Sun, 6 Jul 2025 22:07:38 +0800 Subject: [PATCH] =?UTF-8?q?fix(auth):=20=E4=BF=AE=E5=A4=8D=E9=80=80?= =?UTF-8?q?=E5=87=BA=E7=99=BB=E5=BD=95=E6=97=B6token=E6=97=A0=E6=95=88?= =?UTF-8?q?=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 优化退出登录流程,先清除本地缓存再调用后端接口 - 确保即使后端接口失败也能正常清理前端状态 - 添加fetchLogout接口调用,保证前后端状态同步 - 修复退出登录时序问题,避免token状态不一致 --- src/store/auth.ts | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/src/store/auth.ts b/src/store/auth.ts index 01b37cc..4a1d47c 100644 --- a/src/store/auth.ts +++ b/src/store/auth.ts @@ -1,5 +1,5 @@ import { router } from '@/router' -import { fetchLogin, fetchLoginUserInfo } from '@/service/api/auth' +import { fetchLogin, fetchLoginUserInfo, fetchLogout } from '@/service/api/auth' import { local } from '@/utils' import { useRouteStore } from './router' import { useTabStore } from './tab' @@ -25,16 +25,27 @@ export const useAuthStore = defineStore('auth-store', { /* 登录退出,重置用户信息等 */ async logout() { const route = unref(router.currentRoute) - // 清除本地缓存 + + // 先清除本地缓存,立即使token失效 this.clearAuthStorage() + // 重置当前存储库 + this.$reset() // 清空路由、菜单等数据 const routeStore = useRouteStore() routeStore.resetRouteStore() // 清空标签栏数据 const tabStore = useTabStore() tabStore.clearAllTabs() - // 重置当前存储库 - this.$reset() + + // 最后调用后端退出登录接口 + try { + await fetchLogout() + } + catch (error) { + // 后端接口调用失败不影响前端清理 + console.warn('后端退出登录接口调用失败:', error) + } + // 重定向到登录页 if (route.meta.requiresAuth) { router.push({ @@ -67,9 +78,13 @@ export const useAuthStore = defineStore('auth-store', { if (!userInfoResult.isSuccess) return - // 处理登录信息 + // 处理登录信息 - 转换后端返回的数据结构 const userInfo = { - ...userInfoResult.data, + id: userInfoResult.data.loginUser.userId, + userId: userInfoResult.data.loginUser.userId, + userName: userInfoResult.data.loginUser.userName, + avatar: userInfoResult.data.loginUser.avatar, + role: userInfoResult.data.roles, accessToken: data.tokenValue, refreshToken: data.tokenValue, // 如果后端没有单独的refreshToken,暂时使用相同值 } @@ -100,5 +115,15 @@ export const useAuthStore = defineStore('auth-store', { path: query.redirect || '/', }) }, + + /* 更新用户信息 */ + updateUserInfo(updates: Partial) { + if (this.userInfo) { + // 更新内存中的用户信息 + this.userInfo = { ...this.userInfo, ...updates } + // 更新本地存储 + local.set('userInfo', this.userInfo) + } + }, }, })