51 lines
1.0 KiB
TypeScript
51 lines
1.0 KiB
TypeScript
import request from '@/utils/request'
|
|
import { defineStore } from 'pinia'
|
|
import { computed, reactive, ref, watch } from 'vue'
|
|
|
|
interface UserInfo {
|
|
id: string
|
|
username: string
|
|
gender: number
|
|
birthday: string
|
|
avatar: string
|
|
openId: string
|
|
}
|
|
const defaultUserInfo: UserInfo = {
|
|
id: '',
|
|
username: '',
|
|
gender: 0,
|
|
birthday: '',
|
|
avatar: '',
|
|
openId: ''
|
|
}
|
|
export default defineStore('user', () => {
|
|
const token = ref(localStorage.getItem('token') || '')
|
|
watch(token, (val) => {
|
|
localStorage.setItem('token', val)
|
|
})
|
|
const profile = reactive({...defaultUserInfo})
|
|
watch(
|
|
token,
|
|
(val) => {
|
|
if (!val) return
|
|
request<UserInfo>('GET', '/api/profile').then((res) => {
|
|
Object.assign(profile, res)
|
|
})
|
|
},
|
|
{ immediate: true }
|
|
)
|
|
const isLogin = computed(() => !!token.value && !!profile.id)
|
|
const logout = () => {
|
|
token.value = ''
|
|
Object.assign(profile, {...defaultUserInfo})
|
|
// profile.avatar = ''
|
|
}
|
|
// 自动备份
|
|
return {
|
|
token,
|
|
profile,
|
|
isLogin,
|
|
logout
|
|
}
|
|
})
|