返回
小程序实战:打造万能验证码定时器
前端
2023-09-03 06:39:00
一、设计思路
小程序验证码定时器主要有三个关键步骤:
- 校验手机号是否正确
- 开启倒计时
- 调用获取验证码接口
二、实战步骤
1. 校验手机号
const validatePhone = (phone) => {
// 正则表达式校验手机号格式
const reg = /^1\d{10}$/;
return reg.test(phone);
};
2. 开启倒计时
let time = 60; // 初始时间:60s
const startTimer = () => {
if (time === 0) {
// 倒计时结束,按钮可点击
time = 60; // 初始化时间
btn.removeAttribute("disabled");
} else {
// 倒计时中,按钮不可点击
btn.setAttribute("disabled", "disabled");
time--;
setTimeout(startTimer, 1000); // 定时器:每秒执行一次
}
};
3. 调用获取验证码接口
const getVerificationCode = () => {
// 发送获取验证码请求
wx.request({
url: "xxx",
data: {
phone: phone,
},
success: (res) => {
if (res.data.code === 0) {
// 获取验证码成功
startTimer(); // 开启倒计时
} else {
// 获取验证码失败
wx.showToast({
title: res.data.msg,
icon: "none",
});
}
},
fail: () => {
// 请求失败
wx.showToast({
title: "网络错误",
icon: "none",
});
},
});
};
三、封装通用组件
上述代码可封装为一个通用的验证码定时器组件:
Component({
properties: {
phone: {
type: String,
value: "",
},
},
data: {
time: 60, // 初始时间:60s
disabled: false, // 按钮是否可点击
},
methods: {
validatePhone() {
// 校验手机号
return validatePhone(this.data.phone);
},
startTimer() {
// 开启倒计时
let that = this;
let interval = setInterval(() => {
if (that.data.time === 0) {
clearInterval(interval);
that.setData({
time: 60,
disabled: false,
});
} else {
that.setData({
time: that.data.time - 1,
disabled: true,
});
}
}, 1000);
},
getVerificationCode() {
// 校验手机号
if (!this.validatePhone()) {
wx.showToast({
title: "请输入正确的手机号",
icon: "none",
});
return;
}
// 开启倒计时
this.startTimer();
// 发送获取验证码请求
// ...
},
},
});
四、结语
通过本文的深入讲解,你已掌握了小程序验证码定时器的设计、实现和封装技巧。学会了这个万能验证码定时器,你就能轻松提升小程序的用户体验,保障应用的安全性。赶快动手实践,提升你的开发技能吧!