2026-04-20 11:21:21 +08:00
|
|
|
|
// 每一个存储的模块,命名规则use开头,store结尾
|
2026-05-22 13:53:07 +08:00
|
|
|
|
import { AccountLogout } from '@/api/account'
|
2026-04-20 11:21:21 +08:00
|
|
|
|
import { defineStore } from 'pinia'
|
|
|
|
|
|
import { ref, computed } from 'vue'
|
|
|
|
|
|
import { removeLocal, setLocal } from '@/utils/local'
|
|
|
|
|
|
import MyEvent from '@/utils/myEvent'
|
2026-05-22 13:53:07 +08:00
|
|
|
|
import router from '@/router'
|
2026-04-20 11:21:21 +08:00
|
|
|
|
export const useUserInfoStore = defineStore('userInfo', () => {
|
2026-05-21 10:48:53 +08:00
|
|
|
|
const state = ref({
|
2026-05-21 11:04:12 +08:00
|
|
|
|
userInfo: {
|
|
|
|
|
|
userId: "",
|
|
|
|
|
|
email: "",
|
|
|
|
|
|
username: "",
|
|
|
|
|
|
accessToken: "",
|
|
|
|
|
|
expiresIn: "",
|
|
|
|
|
|
},
|
|
|
|
|
|
token: ''
|
2026-05-21 10:48:53 +08:00
|
|
|
|
})
|
2026-04-20 11:21:21 +08:00
|
|
|
|
|
2026-05-21 10:48:53 +08:00
|
|
|
|
// actions
|
|
|
|
|
|
const setUserInfo = (data: any) => {
|
|
|
|
|
|
state.value.userInfo = data
|
2026-05-21 11:04:12 +08:00
|
|
|
|
setToken(data.accessToken)
|
2026-05-21 10:48:53 +08:00
|
|
|
|
}
|
2026-04-20 11:21:21 +08:00
|
|
|
|
|
2026-05-21 10:48:53 +08:00
|
|
|
|
const setToken = (data: string) => {
|
|
|
|
|
|
state.value.token = data
|
|
|
|
|
|
setLocal(data, 'token')
|
|
|
|
|
|
}
|
2026-04-20 11:21:21 +08:00
|
|
|
|
|
2026-05-22 13:53:07 +08:00
|
|
|
|
const logout = async (reload: boolean = false) => {
|
2026-05-21 10:48:53 +08:00
|
|
|
|
// 处理退出登录的一些逻辑
|
2026-05-22 13:53:07 +08:00
|
|
|
|
const userId = state.value.userInfo.userId
|
|
|
|
|
|
if (userId) await AccountLogout({ userId })
|
|
|
|
|
|
state.value.userInfo = {
|
|
|
|
|
|
userId: "",
|
|
|
|
|
|
email: "",
|
|
|
|
|
|
username: "",
|
|
|
|
|
|
accessToken: "",
|
|
|
|
|
|
expiresIn: "",
|
|
|
|
|
|
}
|
|
|
|
|
|
state.value.token = ''
|
|
|
|
|
|
removeLocal('token')
|
|
|
|
|
|
if (reload) router.go(0)
|
|
|
|
|
|
|
2026-05-21 10:48:53 +08:00
|
|
|
|
}
|
2026-04-20 11:21:21 +08:00
|
|
|
|
|
2026-05-21 10:48:53 +08:00
|
|
|
|
return {
|
|
|
|
|
|
state,
|
|
|
|
|
|
setToken,
|
|
|
|
|
|
setUserInfo,
|
2026-05-21 11:04:12 +08:00
|
|
|
|
logout
|
2026-05-21 10:48:53 +08:00
|
|
|
|
}
|
2026-04-20 11:21:21 +08:00
|
|
|
|
})
|