Vue3 hook實(shí)現(xiàn)頁(yè)面刷新繼續(xù)倒計(jì)時(shí)

/**
 * 倒計(jì)時(shí),主要用于發(fā)送短信驗(yàn)證碼倒計(jì)時(shí)
 * 利用到期時(shí)間做倒計(jì)時(shí),解決倒計(jì)時(shí)在頁(yè)面關(guān)閉后就被不會(huì)更新的痛點(diǎn)
 */
import { onMounted, ref } from "vue";
export function useCountDown() {
  const timeLeft = ref<number>(0);
  onMounted(() => {
    // 計(jì)算當(dāng)前時(shí)間到可以重新獲取時(shí)間中間相差多少秒
    if (getRetrieveTime()) {
      const diff = getRetrieveTime() - new Date().getTime();
      if (diff <= 0) {
        // 倒計(jì)時(shí)結(jié)束了,可以獲取驗(yàn)證碼
        timeLeft.value = 0;
      } else {
        // 倒計(jì)時(shí)沒(méi)有結(jié)束,繼續(xù)倒計(jì)時(shí)
        timeLeft.value = Math.ceil(diff / 1000);
        start();
      }
    }
  });
  /**
   * 存儲(chǔ)可以重新獲取的時(shí)間
   */
  const setRetrieveTime = (count: number) => {
    localStorage.setItem(
      "retrieveTime",
      new Date(new Date().getTime() + count * 1000).getTime() + ""
    );
  };
  /**
   * 獲取可以重新獲取的時(shí)間
   */
  const getRetrieveTime = () => {
    return Number(localStorage.getItem("retrieveTime") || "0");
  };
  /**
   * 啟動(dòng)循環(huán)
   */
  const start = () => {
    setTimeout(() => {
      if (timeLeft.value > 0) {
        timeLeft.value--;
        start();
      }
    }, 1000);
  };

  /**
   * 點(diǎn)擊開(kāi)啟倒計(jì)時(shí)
   * @param count 倒計(jì)時(shí)的時(shí)間,單位秒(s)
   */
  const startCountDown = (count: number) => {
    timeLeft.value = count;
    setRetrieveTime(count);
    start();
  };
  return {
    timeLeft,
    startCountDown,
  };
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容