本文主要是介绍vue ts 本地缓存数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
vue ts 本地缓存数据
需求是:给每日最高热度的数据,每个用户弹窗三次,持续五秒
// 每日最高热度 弹窗三次
const popupKey = 'dailyPopupCount_';
const today = new Date().toISOString().split('T')[0]; // dailyPopupCount_2024-08-26
const popupCount = ref(parseInt(localStorage.getItem(`${popupKey}${today}`) || '0', 10));
export const showHost = ref(false); //最高热度弹窗
export const countdown = ref(0);
export let timer: number | null | any = null;
// 检查并更新弹窗显示状态
export const checkAndShowPopup = () => {if (popupCount.value < 3) {showHost.value = true;countdown.value = 5; // 初始化倒计时为5秒timer = setInterval(updateCountdown, 1000); // 每秒更新一次倒计时popupCount.value++;localStorage.setItem(`${popupKey}${today}`, popupCount.value.toString());}// 遍历 localStorage 中的所有项for (let i = localStorage.length - 1; i >= 0; i--) {const key = localStorage.key(i);if (key) {// 检查键是否以 dailyPopupCount_ 开头,并且是否不代表今天的日期if (key.startsWith(popupKey) && !key.endsWith(today)) {// 移除这个键localStorage.removeItem(key);}}}
};// 手动关闭弹窗
export const hidePopup = () => {showHost.value = false;if (timer) {timeFun();clearTime();}
};const timeFun = () => {// 隐藏弹窗并更新弹窗次数showHost.value = false;localStorage.setItem(`${popupKey}${today}`, popupCount.value.toString());
};const clearTime = () => {clearInterval(timer!);timer = null;
};// 更新倒计时
const updateCountdown = () => {if (countdown.value > 0) {countdown.value--;} else {timeFun();clearTime();}
};
这篇关于vue ts 本地缓存数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!