This time I will show you how to use Vue to implement the countdown button, and what are the precautions for using Vue to implement the countdown button. The following is a practical case, let's take a look.
In project development, we often encounter a button that sends a verification code and has a 60-second countdown after clicking it. It is very common but also very simple, but there are certain places that you need to pay attention to when writing this button. Next, I will write it down today. If you have any questions, please correct me! The completed effect is as follows: 
<button class="button" @click="countDown">
{{content}}
</button>
...
data () {
return {
content: '发送验证码', // 按钮里显示的内容
totalTime: 60 //记录具体倒计时时间
}
},
methods: {
countDown() {
let clock = window.setInterval(() => {
this.total--
this.content = this.total + 's后重新发送'
},1000)
}
} 
You can still click during the countdown.
The countdown has not been cleared yet.
countDown () {
this.content = this.totalTime + 's后重新发送' //这里解决60秒不见了的问题
let clock = window.setInterval(() => {
this.totalTime--
this.content = this.totalTime + 's后重新发送'
if (this.totalTime < 0) { //当倒计时小于0时清除定时器
window.clearInterval(clock)
this.content = '重新发送验证码'
this.totalTime = 60
}
},1000)
}, 
data () {
return {
content: '发送验证码',
totalTime: 10,
canClick: true //添加canClick
}
}
...
countDown () {
if (!this.canClick) return //改动的是这两行代码
this.canClick = false
this.content = this.totalTime + 's后重新发送'
let clock = window.setInterval(() => {
this.totalTime--
this.content = this.totalTime + 's后重新发送'
if (this.totalTime < 0) {
window.clearInterval(clock)
this.content = '重新发送验证码'
this.totalTime = 10
this.canClick = true //这里重新开启
}
},1000)
} 
<button class="button" :class="{disabled: !this.canClick}" @click="countDown">
...
.disabled{
background-color: #ddd;
border-color: #ddd;
color:#57a3f3;
cursor: not-allowed; // 鼠标变化
}
How to use Vue to write a two-way data binding
The above is the detailed content of How to use Vue to implement a countdown button. For more information, please follow other related articles on the PHP Chinese website!