user.js 1.7 KB

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