一、vue 实现登录倒计时
- 在
data
中定义 computeTime
,默认为 0, 为倒计时的时间,代码如下所示:
data() {
return {
computeTime: 0
}
}
- 在手机号
input
输入框旁边的按钮上,动态设置 !rightPhone
才 disabled
禁止,也说明正确的手机号就可以点击,错误的不能够点击,为禁止状态。同时,对象样式绑定当为rightPhone
进行设置,并且绑定点击事件getCode
进行发送验证码。由于如果点击,默认会对整个表单的数据进行提交,所以需要阻止默认行为,通过 @click.prevent
进行阻止表单数据的提交。显示的文本内容也是根据 computeTime
的值进行设置,当 computeTime>0
就显示倒计时的时间,此时是禁止状态,而 computeTime<0
就显示默认文本,此时是正常状态,代码如下所示:
<section class="login_message">
<input type="tel" maxlength="11" placeholder="手机号" v-model="phone">
<button :disabled="!rightPhone" class="get_verification" :class="{rightPhone: rightPhone}" @click.prevent="getCode">{{ computeTime>0 ? `已发送(${computeTime}s)` : '获取验证码'}}</button>
</section>
- 在
methods
中,定义 getCode
方法,点击获取验证码。如果 this.computeTime
不存在,说明当前没有计时,那么就启动倒计时,设置 computeTime
的值为 30。写setInterval
定时器,每过一秒,computeTime
的值都会递减。如果 computeTime
的值小于等于0,那么就停止倒计时,清除定时器,最后发送 ajax
请求,向指定的手机号发送验证码短信,代码如下所示:
methods: {
async getCode () {
if (!this.computeTime) {
this.computeTime = 30
const intervalId = setInterval(() => {
this.computeTime--
if ( this.computeTime <=0) {
clearInterval(intervalId)
}
}, 1000)
const result = await reqSendCode(this.phone)
if (result.code === 1) {
this.showAlert(result.msg)
if (this.computeTime) {
this.computeTime = 0
clearInterval(this.intervalId)
this.intervalId = undefined
}
}
}
}
}