/**
* 倒計(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,
};
}
Vue3 hook實(shí)現(xiàn)頁(yè)面刷新繼續(xù)倒計(jì)時(shí)
?著作權(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ù)。
【社區(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)容
- 部分 html 代碼 部分 javascript
- 不說(shuō)廢話,看這個(gè)文檔的大部分都是程序員,所以直接上代碼了。 首先寫(xiě)了一個(gè) CookieUtils.tsx 工具類(lèi) ...
- 使用場(chǎng)景: 一般多個(gè)定時(shí)器同時(shí)使用的場(chǎng)景主要應(yīng)用在限時(shí)活動(dòng)或者限時(shí)搶購(gòu)商品等,如一個(gè)頁(yè)面存在多個(gè)商品,且每個(gè)商品都...
- //30s后跳轉(zhuǎn)到目標(biāo)頁(yè)面無(wú)url則為每30s刷新自身 //定時(shí)器,倒計(jì)時(shí)-----