auth.js
1.19 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
import { ref, provide, inject, onMounted } from 'vue'
// 创建认证上下文的key
const authKey = Symbol('auth')
/**
* 提供认证功能的组合式函数
*/
export function provideAuth() {
const currentUser = ref(null)
const loading = ref(true)
// 初始化时检查本地存储的用户信息
onMounted(() => {
const savedUser = localStorage.getItem('currentUser')
if (savedUser) {
currentUser.value = JSON.parse(savedUser)
}
loading.value = false
})
// 登录函数
const login = (userData) => {
currentUser.value = userData
localStorage.setItem('currentUser', JSON.stringify(userData))
return true
}
// 登出函数
const logout = () => {
currentUser.value = null
localStorage.removeItem('currentUser')
}
// 提供认证上下文
provide(authKey, {
currentUser,
loading,
login,
logout
})
return {
currentUser,
loading,
login,
logout
}
}
/**
* 使用认证功能的组合式函数
* @returns {Object} 认证上下文值
*/
export function useAuth() {
const auth = inject(authKey)
if (!auth) {
throw new Error('useAuth 必须在 provideAuth 的范围内使用')
}
return auth
}