添加了快速判断是否登录的方法
This commit is contained in:
parent
817f39e11e
commit
a9e14ff5e2
@ -1,5 +1,5 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { ref } from 'vue';
|
||||
import { ref, computed } from 'vue';
|
||||
import { authService } from '../api/authService';
|
||||
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';
|
||||
import { createPinia } from 'pinia';
|
||||
@ -10,18 +10,16 @@ const pinia = createPinia();
|
||||
pinia.use(piniaPluginPersistedstate);
|
||||
|
||||
// 定义 auth store,包含用户认证相关状态和方法
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
// 用户访问令牌
|
||||
export const userStore = defineStore('auth', () => {
|
||||
const accessToken = ref('');
|
||||
// 用户刷新令牌
|
||||
const refreshToken = ref('');
|
||||
// 用户角色
|
||||
const role = ref('');
|
||||
// 用户名
|
||||
const username = ref('');
|
||||
// 用户 ID
|
||||
const userId = ref<number | null>(null);
|
||||
|
||||
// 计算属性,用于快速判断用户是否登录
|
||||
const isLoggedIn = computed(() => !!accessToken.value);
|
||||
|
||||
// 设置访问和刷新令牌的方法
|
||||
function setTokens(tokens: { access_token: string; refresh_token: string }) {
|
||||
accessToken.value = tokens.access_token;
|
||||
@ -66,18 +64,18 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
}
|
||||
}
|
||||
|
||||
return { accessToken, refreshTokenToken: refreshToken, role, username, userId, login, logout, refreshTokenMethod };
|
||||
return { accessToken, refreshTokenToken: refreshToken, role, username, userId, isLoggedIn, login, logout, refreshTokenMethod };
|
||||
}, {
|
||||
persist: true,
|
||||
});
|
||||
|
||||
// 使用插件进行持久化,监听 store 变化并保存到本地存储
|
||||
useAuthStore().$subscribe((mutation, state) => {
|
||||
userStore().$subscribe((mutation, state) => {
|
||||
localStorage.setItem('authStore', JSON.stringify(state));
|
||||
});
|
||||
|
||||
// 监听 action 执行,登录和刷新令牌后保存状态到本地存储
|
||||
useAuthStore().$onAction(({ name, store, args, after, onError }) => {
|
||||
userStore().$onAction(({ name, store, args, after, onError }) => {
|
||||
if (name === 'login' || name === 'refreshTokenMethod') {
|
||||
after(() => {
|
||||
localStorage.setItem('authStore', JSON.stringify(store.$state));
|
||||
@ -88,5 +86,5 @@ useAuthStore().$onAction(({ name, store, args, after, onError }) => {
|
||||
// 初始化时从本地存储恢复状态
|
||||
const persistedState = JSON.parse(localStorage.getItem('authStore') || '{}');
|
||||
if (persistedState.accessToken && persistedState.refreshTokenToken && persistedState.role && persistedState.username && persistedState.userId !== null) {
|
||||
useAuthStore().$patch(persistedState);
|
||||
}
|
||||
userStore().$patch(persistedState);
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user