userStore.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import {defineStore} from "pinia";
  2. import type User from "@/mode/User";
  3. import type UserSimple from "@/mode/UserSimple";
  4. import UserApi from "@/api/UserApi";
  5. export interface State {
  6. user: User | null;
  7. userMap: Map<string, UserSimple>;
  8. }
  9. // defineStore 调用后返回一个函数,调用该函数获得 Store 实体
  10. export const useUserStore = defineStore({
  11. // id: 必须的,在所有 Store 中唯一
  12. id: "user_store",
  13. // state: 返回对象的函数
  14. state: (): State => ({
  15. user: null,
  16. userMap: new Map<string, UserSimple>(),
  17. }),
  18. // 开启数据缓存
  19. persist: {
  20. enabled: true,
  21. strategies: [
  22. {
  23. key: 'user',
  24. storage: localStorage,
  25. paths: ['user']
  26. }
  27. ]
  28. },
  29. getters: {
  30. getMapUser: (state) => {
  31. return (id: string) => {
  32. return state.userMap.get(id)
  33. }
  34. }
  35. },
  36. actions: {
  37. setUser(user: User): void {
  38. this.user = user;
  39. },
  40. getUser(): User | null {
  41. return this.user;
  42. },
  43. getCacheUser(userId:string): UserSimple | undefined {
  44. return this.userMap?this.userMap.get(userId):undefined;
  45. },
  46. storeUser(userId: string,user: UserSimple): void {
  47. this.userMap.set(userId,user);
  48. },
  49. async loadMapUser(id: string) {
  50. return UserApi.getUser(id).then((res) => {
  51. if (res.data) {
  52. this.storeUser(id, res.data)
  53. }
  54. })
  55. }
  56. },
  57. });