user.js 916 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { defineStore } from 'pinia'
  2. import { login, loginByCode, logout } from '../services/common'
  3. export const useUserStore = defineStore('user', () => {
  4. const userInfo = ref(uni.getStorageSync('userInfo'))
  5. const setUserInfo = data => {
  6. userInfo.value = data
  7. uni.setStorageSync('userInfo', data)
  8. }
  9. const token = ref(uni.getStorageSync('token') || '')
  10. const setToken = data => {
  11. token.value = data
  12. uni.setStorageSync('token', data)
  13. }
  14. const login = data => {
  15. return login(data).then(res => {
  16. setUserInfo(res.userInfo)
  17. setToken(res.token)
  18. })
  19. }
  20. const loginByOpenId = data => {
  21. return loginByCode().then(res => {
  22. setUserInfo(res.userInfo)
  23. setToken(res.token)
  24. })
  25. }
  26. const logout = () => {
  27. return new Promise(resolve => {
  28. setUserInfo({})
  29. setToken('')
  30. resolve()
  31. })
  32. }
  33. return {
  34. userInfo,
  35. setUserInfo,
  36. token,
  37. setToken,
  38. login,
  39. loginByOpenId,
  40. logout
  41. }
  42. })