user.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import { defineStore } from 'pinia';
  2. import { clone, cloneDeep } from 'lodash-es';
  3. import { getUserInfo } from '@/api/user';
  4. // 默认用户信息
  5. const defaultUserInfo = {
  6. avatar: '', // 头像
  7. nickname: '', // 昵称
  8. gender: 0, // 性别
  9. mobile: '', // 手机号
  10. point: 0, // 积分
  11. };
  12. // 默认账户信息
  13. const defaultAccountInfo = {
  14. accessToken: '',
  15. expiresTime: '',
  16. openid: '',
  17. refreshToken: '',
  18. userId: ''
  19. }
  20. const user = defineStore({
  21. id: 'user',
  22. state: () => ({
  23. userInfo: {}, // 用户信息
  24. isLogin: !!uni.getStorageSync('token'), // 登录状态
  25. lastUpdateTime: 0, // 上次更新时间
  26. accountInfo: cloneDeep(defaultAccountInfo), // 账号信息
  27. }),
  28. actions: {
  29. // 获取用户信息
  30. async getInfo() {
  31. const { code, data } = await getUserInfo({ userId: this.accountInfo.userId });
  32. if (code !== 0) {
  33. return;
  34. }
  35. this.userInfo = data;
  36. return Promise.resolve(data);
  37. },
  38. // 设置 token
  39. setToken(token = '', refreshToken = '') {
  40. if (token === '') {
  41. this.isLogin = false;
  42. uni.removeStorageSync('token');
  43. uni.removeStorageSync('refresh-token');
  44. } else {
  45. this.isLogin = true;
  46. uni.setStorageSync('token', token);
  47. uni.setStorageSync('refresh-token', refreshToken);
  48. this.loginAfter();
  49. }
  50. return this.isLogin;
  51. },
  52. // 更新用户相关信息 (手动限流,5 秒之内不刷新)
  53. async updateUserData() {
  54. if (!this.isLogin) {
  55. this.resetUserData();
  56. return;
  57. }
  58. // 防抖,5 秒之内不刷新
  59. const nowTime = new Date().getTime();
  60. if (this.lastUpdateTime + 5000 > nowTime) {
  61. return;
  62. }
  63. this.lastUpdateTime = nowTime;
  64. // 获取最新信息
  65. // await this.getInfo();
  66. this.getWallet();
  67. return this.userInfo;
  68. },
  69. // 重置用户默认数据
  70. resetUserData() {
  71. // 清空 token
  72. this.setToken();
  73. // 清空用户相关的缓存
  74. this.userInfo = clone(defaultUserInfo);
  75. this.accountInfo = cloneDeep(defaultAccountInfo);
  76. },
  77. // 登录后,加载各种信息
  78. async loginAfter() {
  79. await this.updateUserData();
  80. },
  81. // 登出系统
  82. async logout() {
  83. this.resetUserData();
  84. return !this.isLogin;
  85. },
  86. },
  87. persist: {
  88. enabled: true,
  89. strategies: [
  90. {
  91. key: 'user-store',
  92. },
  93. ],
  94. },
  95. });
  96. export default user;