- 新增 pinia-plugin-persistedstate 实现用户状态本地存储 - 重构 API 响应类型为统一模块管理 - 优化路由守卫逻辑,支持 token 自动登录 - 修复权限检查逻辑错误,调整 AI 聊天页访问权限 - 新增用户信息获取接口及类型定义
44 lines
1.1 KiB
TypeScript
44 lines
1.1 KiB
TypeScript
import { defineStore } from "pinia";
|
|
import ACCESS_ENUM from "../access/accessEnum";
|
|
import type { LoginUesr } from "../store/types";
|
|
import { getUserInfoByToken } from "@/api/auth/user";
|
|
/**
|
|
*
|
|
*/
|
|
export const useUserStore = defineStore("user", {
|
|
state: () => ({
|
|
loginUser: {
|
|
userName: "未登录",
|
|
userRole: ACCESS_ENUM.NOT_LOGIN,
|
|
} as LoginUesr,
|
|
}),
|
|
persist: {
|
|
key: "user-store",
|
|
storage: localStorage,
|
|
pick: ["loginUser"], // 只持久化 loginUser
|
|
},
|
|
actions: {
|
|
// 获取登录用户
|
|
async getLoginUser() {
|
|
try {
|
|
const res = await getUserInfoByToken();
|
|
console.log("获取登录用户成功", res);
|
|
if(res.data.success === true){
|
|
this.updateUserLoginStatus(res.data.data);
|
|
}
|
|
}catch(e) {
|
|
console.error("获取登录用户失败", e);
|
|
// 网络错误情况也视为未登录
|
|
this.loginUser = {
|
|
...this.loginUser,
|
|
userRole: ACCESS_ENUM.NOT_LOGIN,
|
|
};
|
|
}
|
|
},
|
|
// 手动更新用户状态
|
|
updateUserLoginStatus(user: LoginUesr) {
|
|
this.loginUser = user;
|
|
}
|
|
},
|
|
});
|