项目需求,做一个普通的验证码倒计时,点击后禁止重复点击,倒计时结束后可以继续点击
效果图:
代码:
<!-- html部分 -->
<van-button size="small" type="primary" :disabled="isSend" @click="countDown">
{{codeName}}
</van-button>
data() {
return {
isSend: false, //禁用
codeName: "发送验证码",
totalTime: 10, //一般是60
timer:'', //定时器
}
},
methods: {
// 验证码倒计时
countDown() {
if (this.isSend) return
// this.getCode() // 获取验证码的接口
this.isSend = true
this.codeName = this.totalTime + 's后重新发送'
this.timer = setInterval(() => {
this.totalTime--
this.codeName = this.totalTime + 's后重新发送'
if (this.totalTime < 0) {
clearInterval(this.timer)
this.codeName = '重新发送验证码'
this.totalTime = 10
this.isSend = false
}
}, 1000)
}
}