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