user.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { defineStore } from "pinia";
  2. import { USER_INFO, TOKEN, OPEN_ID, REDIRECT_KEY } 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. },
  22. actions: {
  23. // 修改用户信息
  24. setUserInfo(e) {
  25. this.userInfo = e;
  26. uni.setStorageSync(USER_INFO, e);
  27. },
  28. // 登录
  29. login(e) {
  30. this.userInfo = e;
  31. this.token = e.token;
  32. this.siteId = e.siteId;
  33. uni.setStorageSync(TOKEN, e.token);
  34. uni.setStorageSync(USER_INFO, e);
  35. setTimeout(() => {
  36. uni.showToast({
  37. title: "登录成功",
  38. duration: 1000,
  39. });
  40. });
  41. },
  42. // 退出之前的操作
  43. beforeLogout() {
  44. uni.showModal({
  45. title: "提示",
  46. content: "确定退出登录吗?",
  47. confirmText: "确定",
  48. success: (res) => {
  49. if (res.confirm) {
  50. this.logout();
  51. } else if (res.cancel) {
  52. }
  53. },
  54. });
  55. },
  56. // 退出登录
  57. async logout(option = {}) {
  58. const options = {
  59. redirct: true,
  60. ...option,
  61. };
  62. try {
  63. const keys = [USER_INFO, TOKEN];
  64. await Promise.all(keys.map((key) => uni.removeStorageSync(key))).then(
  65. () => {
  66. this.userInfo = null;
  67. this.token = "";
  68. options.redirct &&
  69. uni.reLaunch({
  70. url: "/pages/index/index",
  71. });
  72. }
  73. );
  74. return Promise.resolve();
  75. } catch (e) {
  76. console.log("eeee login", e);
  77. //TODO handle the exception
  78. }
  79. },
  80. },
  81. });