一般專案中獲取驗證碼時,設定等待時間60s,倒數計時結束之後才能繼續重新獲取
問題:一開始我只是給按鈕設定了倒數計時,以至於按鈕是一次性的,只能獲取一次,倒數計時結束按鈕恢復可點選狀態,再點選之後按鈕就不倒數計時了...
原因:是因為我在編寫計時器的時候沒清除之前的計時器,沒考慮到:如果獲取驗證碼失敗,計時器依然開始工作,造成定時器結束未銷燬或倒數計時未停止,造成再次點選不是從頭開始
所以再進入新一輪計時時要清楚之前的計時器:
et intervalId = null
const startCountdown = () => {
countdown.value = 60
countdownActive.value = true
if (intervalId) {//清空之前的定時器
clearInterval(intervalId)
}
intervalId = setInterval(() => {
if (countdown.value <= 0) {
clearInterval(intervalId)
intervalId = null
countdown.value = 60
countdownActive.value = false
} else {
countdown.value -= 1
}
}, 1000)
}
例子:
//獲取簡訊驗證碼,限制等待一分鐘再次獲取
//定時器
let intervalId = null
const startCountdown = () => {
countdown.value = 60
countdownActive.value = true
if (intervalId) {//清空之前的定時器
clearInterval(intervalId)
}
intervalId = setInterval(() => {
if (countdown.value <= 0) {
clearInterval(intervalId)
intervalId = null
countdown.value = 60
countdownActive.value = false
} else {
countdown.value -= 1
}
}, 1000)
}
//獲取驗證碼
const handleVerify = async () => {
if (!loginForm.account || !loginForm.captcha) {
message.error("請先填寫手機號和圖形驗證碼");
}else{
let reqData = {
phone: loginForm.account,
code: loginForm.captcha,
captchaId: loginForm.captchaId,
};
countdown.value = 60;
countdownActive.value = true;
try {
let sendVerificationCodeUrl = `/user/sendVerificationCode`;
let result = await axios.post(sendVerificationCodeUrl, reqData);
//重置倒數計時
if (result.data.code == 200) {
message.success("驗證碼已傳送到" + loginForm.account);
}
startCountdown() //傳送成功呼叫倒數計時
} catch (error) {
console.log(error);
message.error(error.response.data.msg);
getCaptcha();
countdownActive.value = false;
loginForm.captcha = null;
}
}
};