我正在参加「码上掘金挑战赛」详情请看:码上掘金挑战赛来了!
今天就在想要写什么文章,突然就想到我正在写的项目上,有一个找回密码的功能,发送验证码按钮禁用事件,于是就写了下来
js项目效果
vue2版本项目实战效果
js项目实现
html
- 只有两个简单的输入框,真实项目可以按照自己的需求去写
<input type="text">
<input type="submit" value="发送">
js
- 本来是想写vue的,但是想到vue只是一个框架,最后还是要用js实现
- 这个小项目还是很容易的
let inps = document.querySelectorAll('input'); // 拿到提交表单元素
let s = 10; // 设置禁用时间
inps[1].addEventListener('click', function () {
this.disabled = true; // 点击过后禁用按钮
let time = setInterval(function () {
if (s == 0) {
clearInterval(time); // 清除定时器
inps[1].value = '发送';
inps[1].disabled = false;
s = 10; //变量需重新赋值
} else {
inps[1].value = '还剩' + s + '秒再次点击';
s--;
}
}, 1000)
});
vue2项目实现代码
- 提示都写在代码旁边
// 点击发送验证码
async sendCaptchaFn () {
this.$notify({ type: 'success', message: '验证码发送成功' }) // vant组件库中的消息提示组件
this.disabledBtn = true // 禁用按钮
await getCaptchaAPI(this.email) // 通过axios发送网络请求
let i = 5 // 定义禁用时间
this.text = `还剩${i}秒再次点击` // 点击按钮后替换文字
const timer = setInterval(() => { // 开启定时器
this.text = `还剩${i - 1}秒再次点击` // 从i-1开始
i--
if (i === 0) {
clearInterval(timer)
this.disabledBtn = false
this.text = '发送验证码'
// 时间到了清除定时器,解除禁用按钮,替换文字
}
}, 1000)
}