在登录页调用了fetchCardInfo接口用于获取用户信息(内容很多有昵称头像钱包等等)然后在首页我的页等需要这个接口里的内容,
问题:那么在首页,我的页,需要再次判断是否有缓存内容吗?还是直接获取即可
首页--
// 使用计算属性从store中获取卡片信息,确保始终返回一个对象以避免undefined错误
const cardInfo = computed(() => {
if (userStore.cardInfo && Object.keys(userStore.cardInfo).length > 0) {
return userStore.cardInfo;
}
// 返回默认空对象,避免在模板中访问属性时出现undefined错误
return {
CardEndDate: '',
CardSerNo: '',
CardTypeName: '',
balance: '0',
EmployeeNo: '',
CardAvailableCredit: 0.00,
BagsInfo: [{
BagsID: null,
BagsType: '',
BagsBalance: 0.00,
BagsExpExpireTime: ''
}]
};
});
onMounted(() => {
// console.log('home--- route.query.OpenID', route.query.OpenID);
// 页面加载时,检查是否已缓存卡片信息,如果没有则获取
if (!userStore.cardInfo || Object.keys(userStore.cardInfo).length === 0) {
fetchCardInfoIfNeeded();
console.log('home---获取卡片信息');
}
});
// 获取卡片信息的函数
const fetchCardInfoIfNeeded = async () => {
console.log('home---获取卡片信息的函数');
try {
await userStore.fetchCardInfo();
console.log('home---获取卡片信息成功:', cardInfo.value.BagsInfo);
} catch (error) {
console.error('home---获取卡片信息失败:', error);
// 可以在这里显示一个提示,告知用户无法获取最新信息
// showToast('无法获取最新卡片信息,请稍后再试');
}
};
我的页——
const cardInfo = computed(() => {
if (userStore.cardInfo && Object.keys(userStore.cardInfo).length > 0) {
return userStore.cardInfo;
}
// 返回包含所有必要属性的默认对象,避免在模板中显示空白
return {
EmployeeName: '',
EmployeeNo: '',
EmployeeStatusName: '',
};
});
登录页-——
try {
await userStore.fetchCardInfo();
console.log('登录---卡片信息获取成功', userStore.cardInfo.BagsInfo);
}
//接口返回数据如——
"CardTypeName": "学生卡",
"CardAccountType": "贷记卡",
"CardStatusName": "正常",
"CardCredit": 1000,
"CardCashBalance": 10,
"CardSubsidyBalance": 0,
"CardAvailableCredit": 1010,
"CardEndDate": "2025-09-01T00:00:00",
"CardBackImage": "http://192.168.80.222:6600/images/CardBack.jpg",
"BagsInfo": [
{
"BagsID": 1,
"BagsType": "现金钱包",
"BagsBalance": 10,
"BagsExpExpireTime": "2025-09-01T00:00:00"
},]
store。user.ts页——
export const useUserStore = defineStore('user', () => {
const cardInfo = ref({})
const isLoading = ref(false)
// 获取并缓存卡片信息
const fetchCardInfo = async () => {
if (isLoading.value) return
isLoading.value = true
try {
const res = await cardInfoApi.getCardInfo()
cardInfo.value = res
// 将卡片信息也存储到localStorage以便持久化
localStorage.setItem('cardInfo', JSON.stringify(res))
return res
} catch (error) {
console.error('获取卡片信息失败:', error)
// 尝试从localStorage读取缓存的卡片信息
const cachedCardInfo = localStorage.getItem('cardInfo')
if (cachedCardInfo) {
cardInfo.value = JSON.parse(cachedCardInfo)
}
throw error
} finally {
isLoading.value = false
}
}
// 清除缓存数据
const clearCache = () => {
cardInfo.value = {}
localStorage.removeItem('cardInfo')
}
return {
isLoading,
fetchCardInfo,
clearCache
}
})