user.js
1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
* @Date: 2025-10-30 10:30:17
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2025-10-30 10:30:26
* @FilePath: /itomix/h5_vite_template/src/stores/user.js
* @Description: 文件描述
*/
import { defineStore } from 'pinia'
import { userApi } from '@/api'
export const useUserStore = defineStore('user', {
state: () => ({
userInfo: null,
token: localStorage.getItem('token') || '',
isLogin: false
}),
getters: {
// 获取用户名
username: (state) => state.userInfo?.username || '',
// 获取用户头像
avatar: (state) => state.userInfo?.avatar || '',
// 是否已登录
hasLogin: (state) => !!state.token && !!state.userInfo
},
actions: {
// 设置 token
setToken(token) {
this.token = token
localStorage.setItem('token', token)
},
// 清除 token
clearToken() {
this.token = ''
localStorage.removeItem('token')
},
// 设置用户信息
setUserInfo(userInfo) {
this.userInfo = userInfo
this.isLogin = true
},
// 清除用户信息
clearUserInfo() {
this.userInfo = null
this.isLogin = false
},
// 登录
async login(loginData) {
const response = await userApi.login(loginData)
const { token, userInfo } = response.data
this.setToken(token)
this.setUserInfo(userInfo)
return response
},
// 获取用户信息
async getUserInfo() {
try {
const response = await userApi.getUserInfo()
this.setUserInfo(response.data)
return response
} catch (error) {
// 如果获取用户信息失败,清除本地存储
this.logout()
throw error
}
},
// 登出
async logout() {
try {
await userApi.logout()
} catch (error) {
console.error('登出失败:', error)
} finally {
this.clearToken()
this.clearUserInfo()
}
}
}
})