user.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. token:'',
  9. userInfo: null, // 用户信息
  10. inpage:false, //是否当前页面
  11. }),
  12. getters: {
  13. // 方便在模板中直接使用
  14. isLoggedIn: (state) => state.isLogin,
  15. },
  16. actions: {
  17. // 打开登录弹框
  18. openLoginModal() {
  19. this.showLoginModal = true;
  20. },
  21. // 关闭登录弹框
  22. closeLoginModal() {
  23. this.showLoginModal = false;
  24. },
  25. async register(userFrom) {
  26. await new Promise(resolve => {
  27. api.post('/wx/register',userFrom).then(({data:res})=>{
  28. if(res.code !== 0){
  29. return uni.showToast({
  30. title: res.msg
  31. })
  32. }
  33. this.showLoginModal = false;
  34. this.isRegister = true;
  35. uni.showToast({
  36. title: '注册成功',
  37. icon: 'success'
  38. });
  39. })
  40. });
  41. },
  42. async login(loginDto) {
  43. await new Promise(resolve => {
  44. api.get('/wx/login',loginDto).then(({data:res})=>{
  45. if(res.code !== 0){
  46. uni.showModal({
  47. title:'温馨提示',
  48. content:res.msg,
  49. showCancel:false
  50. })
  51. return
  52. }
  53. this.showLoginModal = false;
  54. this.isLogin = true;
  55. this.token = res.data?.token;
  56. this.userInfo = res.data;
  57. uni.setStorageSync('token',this.userInfo?.token)
  58. const currentDate = new Date();
  59. const futureDate = new Date(currentDate);
  60. futureDate.setDate(currentDate.getDate() + 7);
  61. uni.setStorageSync('expaireTime',Date.parse(futureDate))
  62. uni.setStorageSync('userInfo',JSON.stringify(this.userInfo))
  63. uni.showToast({
  64. title: '登录成功',
  65. icon: 'success'
  66. });
  67. })
  68. });
  69. },
  70. // 登出操作
  71. logout() {
  72. this.isRegister = false;
  73. this.isLogin = false;
  74. this.userInfo = null;
  75. uni.showToast({
  76. title: '已退出登录',
  77. icon: 'none'
  78. });
  79. },
  80. },
  81. });