user.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /** @format */
  2. import { ref } from 'vue'
  3. import { defineStore } from 'pinia'
  4. import { useCommonStore } from './common'
  5. import { loginApi, logoutApi } from '~/api/model/user'
  6. interface LoginRequestData {
  7. email: string
  8. password: string
  9. type: 'google' | 'email'
  10. }
  11. export const useUserStore = defineStore(
  12. 'user',
  13. () => {
  14. const userInfo = shallowRef<any>()
  15. const token = shallowRef<any>()
  16. const isLogin = computed(() => !!token.value)
  17. const avatar = computed(() => userInfo.value?.avatar)
  18. const nickname = computed(() => userInfo.value?.email)
  19. // 是否提交过的信息
  20. const isCompletedInfo = computed(() => {
  21. return !!(+userInfo.value?.infoState)
  22. })
  23. const updateAccount = (data: any) => {
  24. const commonStore = useCommonStore()
  25. commonStore.pushAccount({ email: data.email, id: data.id, name: `${data.firstName} ${data.lastName}`, type: data.type })
  26. }
  27. /** 登录操作 */
  28. const login = async (params: LoginRequestData) => {
  29. try {
  30. const data: any = await loginApi(params)
  31. const { token: userToken, userInfo: userDataInfo } = data
  32. userInfo.value = userDataInfo
  33. token.value = userToken
  34. ElMessage({
  35. message: 'Login success',
  36. type: 'success',
  37. plain: true,
  38. })
  39. updateAccount(userInfo.value)
  40. }
  41. catch (error) {
  42. return Promise.reject(error)
  43. }
  44. }
  45. const updateUserInfo = (data: any) => {
  46. userInfo.value = { ...userInfo.value, ...data }
  47. updateAccount(userInfo.value)
  48. }
  49. /** 退出登录操作 */
  50. const logout = async () => {
  51. try {
  52. if (token.value) {
  53. await logoutApi()
  54. document.cookie
  55. = 'user=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/'
  56. ElMessage({
  57. message: 'Exit successful',
  58. type: 'success',
  59. plain: true,
  60. })
  61. window.location.reload()
  62. }
  63. }
  64. finally {
  65. token.value = null
  66. userInfo.value = undefined
  67. const router = useRouter()
  68. router.push('/')
  69. }
  70. }
  71. return { userInfo, isCompletedInfo, updateUserInfo, token, login, logout, isLogin, avatar, nickname }
  72. },
  73. {
  74. persist: true,
  75. },
  76. )