user.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { ACCOUNT_KEY, USERINFO_KEY, TOKEN_KEY } from '@/enums/cacheEnums'
  2. import {createPinia, defineStore} from 'pinia'
  3. import { createPersistedState } from 'pinia-plugin-persistedstate'
  4. const pinia = createPinia()
  5. interface UserSate {
  6. userInfos: any
  7. token: string | null
  8. account: string | null
  9. temToken: string | null
  10. }
  11. export const useUserStore = defineStore({
  12. id: 'userStore',
  13. state: (): UserSate => {
  14. const TOKEN = useCookie(TOKEN_KEY)
  15. const ACCOUNT = useCookie(ACCOUNT_KEY)
  16. const USERINFO = useCookie(USERINFO_KEY)
  17. return {
  18. userInfos: USERINFO.value || null,
  19. token: TOKEN.value || null,
  20. account: ACCOUNT.value || null,
  21. temToken: null,
  22. }
  23. },
  24. getters: {
  25. isLogin: (state) => !!state.token,
  26. userInfo: (state) => state.userInfos,
  27. },
  28. actions: {
  29. setUserInfo(userInfos:any) {
  30. const USERINFO = useCookie(USERINFO_KEY)
  31. this.userInfos = userInfos
  32. Object.assign(this.userInfos, userInfos)
  33. USERINFO.value = userInfos
  34. },
  35. setAccount(account: string) {
  36. const ACCOUNT = useCookie(ACCOUNT_KEY)
  37. this.account = account
  38. ACCOUNT.value = account
  39. },
  40. login(token: string) {
  41. const TOKEN = useCookie(TOKEN_KEY)
  42. this.token = token
  43. TOKEN.value = token
  44. },
  45. logout() {
  46. const TOKEN = useCookie(TOKEN_KEY)
  47. const USERINFO = useCookie(USERINFO_KEY)
  48. this.token = null
  49. this.userInfos = null
  50. USERINFO.value = null
  51. TOKEN.value = null
  52. navigateTo({path: '/'})
  53. if(process.client) window.localStorage.clear();
  54. },
  55. },
  56. persist: process.client && { // 仅在客户端使用
  57. storage: localStorage, // localStorage 本地存储,可替换sessionStorage
  58. },
  59. })
  60. const clearAllCookies = async()=> {
  61. var cookies = document.cookie.split(";");
  62. for (var i = 0; i < cookies.length; i++) {
  63. var cookie = cookies[i];
  64. var eqPos = cookie.indexOf("=");
  65. var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
  66. document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
  67. }
  68. }
  69. // 添加持久化插件到Pinia中
  70. pinia.use(createPersistedState())
  71. export default pinia