Vue 验证码倒计时实现(刷新保持状态)
mConfigs.ver_code_ide 这个为倒计时写入stora的key唯一名称,为了避免系统内,多处倒计时,key不是唯一问题
大家参考倒计时逻辑即可,每个人的项目不同,这里提供大概的实现代码
export default {
name: "bm_phone_login",
data () {
return {
//用户输入信息
input_info: {
phone: "",
code: "",
},
//倒计时
countDownTime: 60,
timeOut: true,
timer: null,
//错误信息
errorFlag: {
phone_empty: false,
phone_err: false,
code_empty: false,
code_err: false
},
//登录按钮禁用
isLoginForbidden: true,
// 获取验证码按钮禁用
getCodeDisabled: true,
// 获取验证码按钮文字
getCodeBtnText: "获取验证码",
countdownIng: false,
}
},
mounted () {
let sendEndTime = localStorage.getItem(`startTime${this.mConfigs.ver_code_ide}`);
if (sendEndTime) {
this.countdown();
}
},
methods: {
/**************************************************************获取验证码**************************************************************/
countdown () {
let that = this;
let startTime = localStorage.getItem(`startTime${that.mConfigs.ver_code_ide}`);
let nowTime = new Date().getTime();
if (startTime) {
let surplus = 60 - parseInt((nowTime - startTime) / 1000, 10);
this.countDownTime = surplus <= 0 ? 0 : surplus;
} else {
this.countDownTime = 60;
localStorage.setItem(`startTime${this.mConfigs.ver_code_ide}`, nowTime);
}
that.timer = setInterval(() => {
that.countDownTime--;
that.getCodeBtnText = that.countDownTime + "秒";
that.getCodeDisabled = true;
that.countdownIng = true;
if (that.countDownTime <= 0) {
localStorage.removeItem(`startTime${this.mConfigs.ver_code_ide}`);
clearInterval(that.timer);
that.countDownTime = 60;
that.timeOut = true;
that.countdownIng = false;
if (that.input_info.phone == "") {
that.getCodeDisabled = true;
} else {
that.getCodeDisabled = false;
}
that.getCodeBtnText = "获取验证码";
}
}, 1000)
},
getVerifyCode () {
let that = this;
let input_phone = this.input_info.phone.replace(/\s*/g, ""); //去除空格
this.$emit('parent_get_code', input_phone, function (flag) {
if (flag) {
//倒计时
if (!that.errorFlag.phone_err && !that.errorFlag.phone_empty) {
// Toast('验证码已发送');
that.countdown();
} else {
that.errorFlag.phone_empty = true;
}
} else {
that.timeOut = true;
}
});
this.timeOut = false;
}
}
</script>
作者: Homegu
出处:https://www.cnblogs.com/codedisco/p/15681824.html
版权:本文采用「署名-非商业性使用-相同方式共享 4.0 国际」知识共享许可协议进行许可。
觉得文章不错,点个关注呗!
分类:
Web前端
, JavaScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理