user.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. api.get('/wx/login',loginDto).then(({data:res})=>{
  44. if(res.code !== 0){
  45. uni.showModal({
  46. title:'温馨提示',
  47. content:res.msg,
  48. showCancel:false
  49. })
  50. return
  51. }
  52. this.showLoginModal = false;
  53. this.isLogin = true;
  54. this.token = res.data?.token;
  55. this.userInfo = res.data;
  56. uni.setStorageSync('token',this.userInfo?.token)
  57. uni.setStorageSync('userInfo',JSON.stringify(this.userInfo))
  58. uni.showToast({
  59. title: '登录成功',
  60. icon: 'success'
  61. });
  62. })
  63. });
  64. },
  65. // 登出操作
  66. logout() {
  67. this.isRegister = false;
  68. this.isLogin = false;
  69. this.userInfo = null;
  70. uni.showToast({
  71. title: '已退出登录',
  72. icon: 'none'
  73. });
  74. },
  75. },
  76. });