From 2259911a8f63950ea9593853b9917a9fc94caa1d Mon Sep 17 00:00:00 2001 From: carry <2641257231@qq.com> Date: Fri, 7 Feb 2025 14:34:31 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/store/userStore.ts | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/store/userStore.ts b/src/store/userStore.ts index 9fc9b20..0ff4d3d 100644 --- a/src/store/userStore.ts +++ b/src/store/userStore.ts @@ -4,25 +4,35 @@ import { authService } from '../api/authService'; import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'; import { createPinia } from 'pinia'; +// 创建 Pinia 实例并使用持久化插件 const pinia = createPinia(); pinia.use(piniaPluginPersistedstate); +// 定义 auth store,包含用户认证相关状态和方法 export const useAuthStore = defineStore('auth', () => { + // 用户访问令牌 const accessToken = ref(''); + // 用户刷新令牌 const refreshToken = ref(''); + // 用户角色 const role = ref(''); + // 用户名 const username = ref(''); + // 用户 ID const userId = ref(null); + // 设置访问和刷新令牌的方法 function setTokens(tokens: { access_token: string; refresh_token: string }) { accessToken.value = tokens.access_token; refreshToken.value = tokens.refresh_token; } + // 设置用户角色的方法 function setRole(userRole: string) { role.value = userRole; } + // 用户登录方法,调用 authService.login 获取令牌并设置状态 async function login(usernameParam: string, password: string) { try { const { access_token, refresh_token, role: userRole, username: userUsername, id: userIdValue } = await authService.login(usernameParam, password); @@ -35,6 +45,7 @@ export const useAuthStore = defineStore('auth', () => { } } + // 用户登出方法,清空所有状态 async function logout() { accessToken.value = ''; refreshToken.value = ''; @@ -43,6 +54,7 @@ export const useAuthStore = defineStore('auth', () => { userId.value = null; } + // 刷新访问令牌的方法,调用 authService.refreshToken 获取新令牌并设置状态 async function refreshTokenMethod() { try { const { access_token, refresh_token } = await authService.refreshToken(refreshToken.value); @@ -57,11 +69,12 @@ export const useAuthStore = defineStore('auth', () => { persist: true, }); -// 使用插件进行持久化 +// 使用插件进行持久化,监听 store 变化并保存到本地存储 useAuthStore().$subscribe((mutation, state) => { localStorage.setItem('authStore', JSON.stringify(state)); }); +// 监听 action 执行,登录和刷新令牌后保存状态到本地存储 useAuthStore().$onAction(({ name, store, args, after, onError }) => { if (name === 'login' || name === 'refreshTokenMethod') { after(() => {