user.js 1.8 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. 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. return uni.showToast({
  46. title: res.msg
  47. })
  48. }
  49. this.showLoginModal = false;
  50. this.isLogin = true;
  51. this.token = res.data?.token;
  52. this.userInfo = res.data;
  53. uni.setStorageSync('token',this.userInfo?.token)
  54. uni.setStorageSync('userInfo',JSON.stringify(this.userInfo))
  55. uni.showToast({
  56. title: '登录成功',
  57. icon: 'success'
  58. });
  59. })
  60. });
  61. },
  62. // 登出操作
  63. logout() {
  64. this.isRegister = false;
  65. this.isLogin = false;
  66. this.userInfo = null;
  67. uni.showToast({
  68. title: '已退出登录',
  69. icon: 'none'
  70. });
  71. },
  72. },
  73. });