index.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { defineStore } from 'pinia';
  2. import { fetchLogin, fetchUserInfo } from '@/api/user';
  3. import { IAuth, IRole, IUser } from '@/interface';
  4. import cache from '@/utils/cache';
  5. type UserRootState = {
  6. userInfo?: IUser;
  7. token?: string | null;
  8. roles?: IRole[];
  9. auths?: IAuth[];
  10. };
  11. export const useUserStore = defineStore('user', {
  12. state: (): UserRootState => {
  13. return {
  14. token: cache.getStorageExp('token'),
  15. roles: undefined,
  16. userInfo: undefined,
  17. auths: undefined,
  18. };
  19. },
  20. actions: {
  21. setUserInfo(res: UserRootState['userInfo']) {
  22. this.userInfo = res;
  23. },
  24. setToken(res: UserRootState['token'], exp: number) {
  25. cache.setStorageExp('token', res, exp);
  26. this.token = res;
  27. },
  28. setRoles(res: UserRootState['roles']) {
  29. this.roles = res;
  30. },
  31. setAuths(res: UserRootState['auths']) {
  32. this.auths = res;
  33. },
  34. logout() {
  35. cache.clearStorage('token');
  36. this.token = undefined;
  37. this.userInfo = undefined;
  38. this.roles = undefined;
  39. },
  40. async pwdLogin({ id, password }) {
  41. try {
  42. const { data: token } = await fetchLogin({
  43. id,
  44. password,
  45. });
  46. this.setToken(token, 24);
  47. return token;
  48. } catch (error: any) {
  49. // 错误返回401,全局的响应拦截会打印报错信息
  50. return null;
  51. }
  52. },
  53. async getUserInfo() {
  54. try {
  55. const { code, data } = await fetchUserInfo();
  56. this.setUserInfo(data);
  57. this.setRoles(data.roles);
  58. this.setAuths(data.auths);
  59. return { code, data };
  60. } catch (error) {
  61. return error;
  62. }
  63. },
  64. },
  65. });