user.js 2.3 KB

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