Vue 封装短信验证码,刷新缓存倒计时

通过本地存储封装短信验证码延时效果,可以防止用户点击刷新,刷新获取的是本地封装的时间,所以刷新不会重置倒计时,亲测有效,希望能够帮到大家。

HTML 部分

<view class="code-box" @click="sendClick">
   {{ btnStatus ? "获取验证码" : `${countDownTime}s后重新获取` }}
</view>

data 部分

 data() {
    return {
     btnStatus: true, //是否可以点击 按钮状态
     countDownTime: 60, //倒计时
     time: {}, //全局定时器
 }
}

函数部分

 methods: {
    //发送验证码
    sendClick() {
      console.log(this.codeForm.phone);
      let reg = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (!reg.test(this.codeForm.phone)) {
        switch (this.codeForm.phone) {
          case "":
            this.showToast("请填写手机号码", "default");
            break;
          default:
            this.showToast("手机号码格式错误", "default");
            break;
        }
      } else {
        //开启倒计时
        let endMsRes = new Date().getTime() + 60000; //当前时间戳加上一分钟的时间戳,相当于当前时间一分钟以后的时间戳
        localStorage.setItem("loginSendTime", JSON.stringify(endMsRes)); // 把这个一分钟时候的事件戳存起来
        this.codeCountDown(endMsRes); // 调用封装的方法,传入当前60秒时间
      }
    },
    //获取短信验证码
    codeCountDown(endMsRes) {
      this.btnStatus = false;
      this.countDownTime = Math.ceil((endMsRes - new Date().getTime()) / 1000); //剩余多少秒
      this.time = setTimeout(() => {
        this.countDownTime--;
        if (this.countDownTime < 1) {
          this.btnStatus = true;
          this.countDownTime = 60;
          localStorage.removeItem("loginSendTime");
          clearTimeout(this.time);
        } else {
          this.codeCountDown(endMsRes);
        }
      }, 1000);
    },

}
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值