需求:获取验证码,刷新将不清除倒计时。

HTML:

SCRIPT:

export default {

data() {

const validatePhone = (rule, value, callback) => {

if (!value) {

callback(new Error("手机号不能为空"));

}

// 使用正则表达式进行验证手机号码

if (!/^1[3456789]\d{9}$/.test(value)) {

callback(new Error("手机号格式不正确"));

}

// 自定义校验规则 需要调用callback()函数!

callback();

};

return {

// 验证码是否CD

codeCd: false,

// CD长度

long: 15,

select: "+86",

input: "",

form: {

phoneNum: null,

checkCode: null,

},

rules: {

phoneNum: [

// { required: true, validator: validatePhone, trigger: "blur" },

{ required: true, message: "请输入手机号码", trigger: "blur" },

],

checkCode: [

{ required: true, message: "验证码不能为空哦!", trigger: "blur" },

],

},

};

},

methods: {

// 获取手机验证码

handleCaptcha(form) {

this.$refs[form].validateField("phoneNum", async (valid) => {

if (!valid) {

console.log(this.select);

// 获取验证码

localStorage.setItem("countdownStart", Date.now());

localStorage.setItem("remainingTime", this.long);

this.startCountdown();

}

});

},

/**

* @description: 开始计时

* @return {void}

*/

startCountdown() {

this.codeCd = true; // 禁用按钮

this.timer = setInterval(() => {

this.long--;

//更新本地倒计时

localStorage.setItem("remainingTime", this.long);

if (this.long === 0) {

this.stopCountdown();

}

}, 1000);

},

/**

* @description: 终止计时

* @return {void}

*/

stopCountdown() {

clearInterval(this.timer); // 清除计时器

this.codeCd = false; // 重新启用按钮

this.long = 15; // 重置倒计时时长

localStorage.removeItem("countdownStart");

localStorage.removeItem("remainingTime");

},

},

created() {

//处理获取手机验证码倒计时

const countdownStart = localStorage.getItem("countdownStart");

const remainingTime = localStorage.getItem("remainingTime");

if (countdownStart && remainingTime) {

//计时开始时的时间到现在经过的时间

const timePassed = (Date.now() - countdownStart) / 1000;

const newRemainingTime = remainingTime - timePassed;

// >0 计时没有结束 则更新剩余时间,继续计时

if (newRemainingTime > 0) {

this.long = Math.ceil(newRemainingTime);

this.startCountdown();

}

}

},

};

CSS:

相关文章

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。