112 lines
2.9 KiB
TypeScript
112 lines
2.9 KiB
TypeScript
![]() |
// 客户端状态管理组合式函数
|
||
|
export default function useClientState() {
|
||
|
const isClient = ref(false)
|
||
|
|
||
|
// 用户信息
|
||
|
const userInfo = ref({
|
||
|
name: '管理员',
|
||
|
role: '系统管理员'
|
||
|
})
|
||
|
|
||
|
// 认证状态
|
||
|
const isAuthenticated = ref(false)
|
||
|
|
||
|
// 初始化客户端状态
|
||
|
const initClientState = () => {
|
||
|
if (process.client) {
|
||
|
isClient.value = true
|
||
|
|
||
|
// 加载用户信息
|
||
|
const adminUser = localStorage.getItem('adminUser')
|
||
|
const authStatus = localStorage.getItem('isAuthenticated')
|
||
|
|
||
|
if (authStatus === 'true' && adminUser) {
|
||
|
try {
|
||
|
const user = JSON.parse(adminUser)
|
||
|
userInfo.value = {
|
||
|
name: user.full_name || user.name || '管理员',
|
||
|
role: user.role === 'admin' ? '管理员' : user.role || '系统管理员'
|
||
|
}
|
||
|
isAuthenticated.value = true
|
||
|
} catch (error) {
|
||
|
console.error('解析用户信息失败:', error)
|
||
|
// 重置状态
|
||
|
isAuthenticated.value = false
|
||
|
userInfo.value = {
|
||
|
name: '管理员',
|
||
|
role: '系统管理员'
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// 更新用户信息
|
||
|
const updateUserInfo = (newUserInfo: { name?: string; role?: string }) => {
|
||
|
if (process.client) {
|
||
|
userInfo.value = { ...userInfo.value, ...newUserInfo }
|
||
|
|
||
|
// 保存到localStorage
|
||
|
const adminUser = {
|
||
|
name: userInfo.value.name,
|
||
|
role: userInfo.value.role
|
||
|
}
|
||
|
localStorage.setItem('adminUser', JSON.stringify(adminUser))
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// 登录
|
||
|
const login = (userData: { name: string; role: string }) => {
|
||
|
if (process.client) {
|
||
|
isAuthenticated.value = true
|
||
|
userInfo.value = userData
|
||
|
|
||
|
localStorage.setItem('adminUser', JSON.stringify(userData))
|
||
|
localStorage.setItem('isAuthenticated', 'true')
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// 登出
|
||
|
const logout = () => {
|
||
|
if (process.client) {
|
||
|
isAuthenticated.value = false
|
||
|
userInfo.value = {
|
||
|
name: '管理员',
|
||
|
role: '系统管理员'
|
||
|
}
|
||
|
|
||
|
localStorage.removeItem('adminUser')
|
||
|
localStorage.removeItem('isAuthenticated')
|
||
|
localStorage.removeItem('user')
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// 设置存储监听器
|
||
|
const setupStorageListener = () => {
|
||
|
if (process.client) {
|
||
|
const handleStorageChange = (e: StorageEvent) => {
|
||
|
if (e.key === 'adminUser' || e.key === 'isAuthenticated') {
|
||
|
initClientState()
|
||
|
}
|
||
|
}
|
||
|
|
||
|
window.addEventListener('storage', handleStorageChange)
|
||
|
|
||
|
// 返回清理函数
|
||
|
return () => {
|
||
|
window.removeEventListener('storage', handleStorageChange)
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return {
|
||
|
isClient: readonly(isClient),
|
||
|
userInfo: readonly(userInfo),
|
||
|
isAuthenticated: readonly(isAuthenticated),
|
||
|
initClientState,
|
||
|
updateUserInfo,
|
||
|
login,
|
||
|
logout,
|
||
|
setupStorageListener
|
||
|
}
|
||
|
}
|