user.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import { defineStore } from "pinia";
  2. import { USER_INFO, TOKEN, OPEN_ID, REDIRECT_KEY, USER_PHONE } from "@/settings/enums.js";
  3. export const useUserStore = defineStore({
  4. id: "app-user",
  5. state: () => ({
  6. userInfo: null,
  7. token: undefined,
  8. siteId: undefined,
  9. openId: undefined,
  10. }),
  11. getters: {
  12. getUserInfo() {
  13. return this.userInfo || uni.getStorageSync(USER_INFO) || {};
  14. },
  15. getToken() {
  16. return this.token || uni.getStorageSync(TOKEN) || "";
  17. },
  18. getOpenId() {
  19. return this.openId || uni.getStorageSync(USER_INFO)?.openId || "";
  20. },
  21. getPhone() {
  22. const info = this.userInfo || uni.getStorageSync(USER_INFO) || {};
  23. return info.phone ?? info.mobile ?? info.contactPhone ?? uni.getStorageSync(USER_PHONE) ?? "";
  24. },
  25. },
  26. actions: {
  27. // 修改用户信息
  28. setUserInfo(e) {
  29. this.userInfo = e;
  30. uni.setStorageSync(USER_INFO, e);
  31. },
  32. // 登录(含微信授权手机号时一并缓存)
  33. login(e) {
  34. this.userInfo = e;
  35. this.token = e.token;
  36. this.siteId = e.siteId;
  37. uni.setStorageSync(TOKEN, e.token);
  38. uni.setStorageSync(USER_INFO, e);
  39. const phone = e.phone ?? e.mobile ?? e.contactPhone ?? "";
  40. if (phone) uni.setStorageSync(USER_PHONE, phone);
  41. setTimeout(() => {
  42. uni.showToast({
  43. title: "登录成功",
  44. duration: 1000,
  45. });
  46. });
  47. },
  48. // 退出之前的操作
  49. beforeLogout() {
  50. uni.showModal({
  51. title: "提示",
  52. content: "确定退出登录吗?",
  53. confirmText: "确定",
  54. success: (res) => {
  55. if (res.confirm) {
  56. this.logout();
  57. } else if (res.cancel) {
  58. }
  59. },
  60. });
  61. },
  62. // 退出登录
  63. async logout(option = {}) {
  64. const options = {
  65. redirct: true,
  66. ...option,
  67. };
  68. try {
  69. const keys = [USER_INFO, TOKEN, USER_PHONE];
  70. await Promise.all(keys.map((key) => uni.removeStorageSync(key))).then(
  71. () => {
  72. this.userInfo = null;
  73. this.token = "";
  74. options.redirct &&
  75. uni.reLaunch({
  76. url: "/pages/index/index",
  77. });
  78. }
  79. );
  80. return Promise.resolve();
  81. } catch (e) {
  82. console.log("eeee login", e);
  83. //TODO handle the exception
  84. }
  85. },
  86. },
  87. });