使用的是vue框架,写了发送验证码功能,后来发现发送验证码后假如剩余40s, 切出去换页面回来还剩40s,就离谱,后来就打算使用缓存来做这个处理了
重点部分的代码我是用注释标注出来
// 发送验证码
async sendCode(newKeyCode = undefined) {
if (!this.isSendCodeActive) {
return;
}
this.sendCodeLoaing = true;
if (!this.globalProcessData.getPublicKey() && !newKeyCode) {
// 没有publicKeyCode,重新获取
this.rsaFailure();
return;
}
const params = {
data: {
mobile: this.codeForm.phoneNum,
},
};
// 将data数据加密并封装为request再请求接口
const request = this.$loginUtils.handleEncryptionRequest(
params,
// 如果公钥不存在则使用刷新的公钥
newKeyCode || this.globalProcessData.getPublicKey()
);
const response = await sendAuthCode(request).catch(() => {});
if (response.code !== 0) {
this.$message({
message: response.msg,
type: 'error',
});
this.sendCodeLoaing = false;
return;
}
if (this.timeObj.codeCount) {
clearTimeout(this.timeObj.codeCount);
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
window.sessionStorage.setItem(
'time_' + location.href,
new Date().getTime()
);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
this.countDownFn(this.countDownNum);
// this.countDownNum--;
},
// 倒计时
countDownFn(time) {
this.countDownNum = time;
if (time === 0) {
this.sendMsg = '重新发送';
this.countDownNum = COUNT_DOWN_NUMBER;
this.sendCodeLoaing = false;
return;
}
this.countDownNum--;
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// 当前时间
const nowTime = new Date().getTime();
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// 上次缓存时间
const lastTime = window.sessionStorage.getItem('time_' + location.href);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// 两次时间差
const diff = nowTime - lastTime / 1000;
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// 如果本地缓存有读秒,则使用本地缓存的读秒
if (diff < 60) {
this.countDownNum = 60 - diff;
}
this.sendMsg = `剩余${this.countDownNum}秒`;
this.timeObj.codeCount = setTimeout(() => {
this.countDownFn(this.countDownNum);
}, 1000);
},