需要修复商城顶部筛选左右滑动问题
This commit is contained in:
70
stores/user.js
Normal file
70
stores/user.js
Normal file
@@ -0,0 +1,70 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import {
|
||||
getToken,
|
||||
getUserInfoData,
|
||||
setUserInfoData,
|
||||
removeUserInfoData
|
||||
} from '@/utils/storage'
|
||||
import { useTokenStore } from './token'
|
||||
import { getUserData } from '@/api'
|
||||
import { ref } from 'vue'
|
||||
|
||||
export const useUserStore = defineStore('user', () => {
|
||||
const { clearToken } = useTokenStore()
|
||||
|
||||
/** 用户信息对象 */
|
||||
const userInfo = ref(JSON.parse(getUserInfoData()) || null)
|
||||
|
||||
/**
|
||||
* 获取用户信息(可从缓存或接口)
|
||||
*/
|
||||
const fetchUserInfo = async () => {
|
||||
// 示例:先尝试从本地缓存读取
|
||||
const cachedToken = getToken()
|
||||
const cachedUserInfo = getUserInfoData()
|
||||
|
||||
if (cachedToken && cachedUserInfo) {
|
||||
userInfo.value = JSON.parse(cachedUserInfo)
|
||||
return
|
||||
}
|
||||
const res = await getUserData()
|
||||
await setUserInfo(res.data)
|
||||
return
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置用户信息
|
||||
*/
|
||||
const setUserInfo = async data => {
|
||||
console.log('存储数据到userInfo==', data)
|
||||
userInfo.value = data
|
||||
// 同步到本地存储
|
||||
setUserInfoData(data)
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除用户信息(退出登录)
|
||||
*/
|
||||
const clearUserInfo = () => {
|
||||
userInfo.value = null
|
||||
clearToken()
|
||||
removeUserInfoData()
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新部分用户信息(例如昵称、头像)
|
||||
*/
|
||||
const updateUserInfo = partialData => {
|
||||
if (!userInfo.value) return
|
||||
userInfo.value = { ...userInfo.value, ...partialData }
|
||||
setUserInfoData(userInfo.value)
|
||||
}
|
||||
|
||||
return {
|
||||
userInfo: userInfo.value,
|
||||
fetchUserInfo,
|
||||
setUserInfo,
|
||||
clearUserInfo,
|
||||
updateUserInfo
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user