获取验证码倒计时

一般项目中获取验证码时,设置等待时间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;
  }
  }
  
};

 

posted @ 2024-09-21 14:22  小小小侠  阅读(8)  评论(0编辑  收藏  举报