user.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import { defineStore } from 'pinia'
  2. import storage from 'store'
  3. import expirePlugin from 'store/plugins/expire'
  4. import { login, uniLogin } from '@/api/login'
  5. import { ChangeUsername, GetUserInfo } from '@/api/user'
  6. storage.addPlugin(expirePlugin)
  7. export const useUserStore = defineStore('user', {
  8. state: () => ({
  9. session: '',
  10. uuid: '',
  11. username: '',
  12. avatar: '',
  13. email: '',
  14. roles: []
  15. }),
  16. actions: {
  17. // 登录
  18. async login(userInfo) {
  19. try {
  20. const res = await login(userInfo)
  21. if (!res || res.code !== 0) throw new Error(res?.msg ?? '登录失败!请稍后再试')
  22. storage.set('user', res.data, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
  23. this.setUser(res.data)
  24. return res.data
  25. } catch (error) {
  26. throw error
  27. }
  28. },
  29. async uniLogin(type, code) {
  30. try {
  31. const res = await uniLogin({type, code})
  32. if (!res || res.code !== 0) throw new Error(res?.msg ?? '登录失败!请稍后再试')
  33. storage.set('user', res.data, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
  34. this.setUser(res.data)
  35. return res.data
  36. } catch (error) {
  37. throw error
  38. }
  39. },
  40. // 更新用户名
  41. async changeName(username) {
  42. try {
  43. const res = await ChangeUsername({ username })
  44. if (!res || res.code !== 0) throw new Error(res?.msg ?? '更新失败!请稍后再试')
  45. this.username = username
  46. storage.set('user', this.$state, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
  47. } catch (error) {
  48. throw error
  49. }
  50. },
  51. // 获取用户信息
  52. async getInfo() {
  53. const user = storage.get('user')
  54. if (user) {
  55. this.setUser(user)
  56. return user
  57. }
  58. return this.$state
  59. },
  60. async getInfoFromServer() {
  61. try {
  62. const res = await GetUserInfo()
  63. if (!res || res.code !== 0) throw new Error(res?.msg ?? '获取用户信息失败!请稍后再试')
  64. storage.set('user', res.data, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
  65. this.setUser(res.data)
  66. return res.data
  67. } catch (error) {
  68. throw error
  69. }
  70. },
  71. // 登出
  72. logout() {
  73. this.setUser({})
  74. storage.remove('user')
  75. },
  76. // 设置用户信息
  77. setUser(user = {}) {
  78. this.session = user.session || ''
  79. this.uuid = user.uuid || ''
  80. this.avatar = user.avatar || ''
  81. this.username = user.username || ''
  82. this.email = user.email || ''
  83. this.roles = user.roles || []
  84. }
  85. }
  86. })