user.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { acceptHMRUpdate, defineStore } from 'pinia';
  2. interface BasicUserInfo {
  3. [key: string]: any;
  4. /**
  5. * 头像
  6. */
  7. avatar: string;
  8. /**
  9. * 用户昵称
  10. */
  11. realName: string;
  12. /**
  13. * 用户角色
  14. */
  15. roles?: string[];
  16. /**
  17. * 用户id
  18. */
  19. userId: string;
  20. /**
  21. * 用户名
  22. */
  23. username: string;
  24. }
  25. interface AccessState {
  26. /**
  27. * 用户信息
  28. */
  29. userInfo: BasicUserInfo | null;
  30. /**
  31. * 用户角色
  32. */
  33. userRoles: string[];
  34. }
  35. /**
  36. * @zh_CN 用户信息相关
  37. */
  38. export const useUserStore = defineStore('core-user', {
  39. actions: {
  40. setUserInfo(userInfo: BasicUserInfo | null) {
  41. // 设置用户信息
  42. this.userInfo = userInfo;
  43. // 设置角色信息
  44. const roles = userInfo?.roles ?? [];
  45. this.setUserRoles(roles);
  46. },
  47. setUserRoles(roles: string[]) {
  48. this.userRoles = roles;
  49. },
  50. },
  51. state: (): AccessState => ({
  52. userInfo: null,
  53. userRoles: [],
  54. }),
  55. });
  56. // 解决热更新问题
  57. const hot = import.meta.hot;
  58. if (hot) {
  59. hot.accept(acceptHMRUpdate(useUserStore, hot));
  60. }