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) + } + }, }, })