vue ts 本地缓存数据

发布于:2024-09-18 ⋅ 阅读:(134) ⋅ 点赞:(0)

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();
  }
};


网站公告

今日签到

点亮在社区的每一天
去签到