user.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import { defineStore } from 'pinia';
  2. import api from '@/common/api/index.js'
  3. export const useUserStore = defineStore('user', {
  4. state: () => ({
  5. isRegister: true, // 是否注册成功
  6. isLogin: false, // 用户是否已登录
  7. showLoginModal: false, // 是否显示登录弹框
  8. registerStep: 0, // 注册步骤:0=未注册,1=填写用户信息,2=添加孩子
  9. token:'',
  10. userInfo: null, // 用户信息
  11. inpage:false, //是否当前页面
  12. }),
  13. getters: {
  14. // 方便在模板中直接使用
  15. isLoggedIn: (state) => state.isLogin,
  16. },
  17. actions: {
  18. // 打开登录弹框
  19. openLoginModal() {
  20. this.showLoginModal = true;
  21. },
  22. // 关闭登录弹框
  23. closeLoginModal() {
  24. this.showLoginModal = false;
  25. this.registerStep = 0;
  26. },
  27. async register(userFrom) {
  28. return new Promise(resolve => {
  29. api.post('/wx/register',userFrom).then(({data:res})=>{
  30. if(res.code !== 0){
  31. uni.showToast({ title: res.msg })
  32. resolve(false)
  33. return
  34. }
  35. // 注册成功,进入第二步添加孩子
  36. this.registerStep = 2;
  37. resolve(true)
  38. })
  39. });
  40. },
  41. // 添加孩子完成后调用,完成整个注册流程
  42. completeRegister() {
  43. this.showLoginModal = false;
  44. this.isRegister = true;
  45. this.isLogin = true;
  46. this.registerStep = 0;
  47. uni.showToast({
  48. title: '注册成功',
  49. icon: 'success'
  50. });
  51. },
  52. async login(loginDto) {
  53. await new Promise(resolve => {
  54. api.get('/wx/login',loginDto).then(({data:res})=>{
  55. if(res.code !== 0){
  56. uni.showModal({
  57. title:'温馨提示',
  58. content:res.msg,
  59. showCancel:false
  60. })
  61. return
  62. }
  63. this.token = res.data?.token;
  64. this.userInfo = res.data;
  65. uni.setStorageSync('token',this.userInfo?.token)
  66. const currentDate = new Date();
  67. const futureDate = new Date(currentDate);
  68. futureDate.setDate(currentDate.getDate() + 7);
  69. uni.setStorageSync('expaireTime',Date.parse(futureDate))
  70. uni.setStorageSync('userInfo',JSON.stringify(this.userInfo))
  71. // 新用户(userLevel=0)需要注册流程
  72. if(res.data?.userLevel === 0) {
  73. this.isRegister = false;
  74. this.registerStep = 1;
  75. } else {
  76. this.showLoginModal = false;
  77. this.isLogin = true;
  78. uni.showToast({
  79. title: '登录成功',
  80. icon: 'success'
  81. });
  82. }
  83. })
  84. });
  85. },
  86. // 登出操作
  87. logout() {
  88. this.isRegister = false;
  89. this.isLogin = false;
  90. this.userInfo = null;
  91. uni.showToast({
  92. title: '已退出登录',
  93. icon: 'none'
  94. });
  95. },
  96. },
  97. });