Home >Web Front-end >JS Tutorial >Vue implements countdown button
This time I will bring you Vue to implement the countdown button. What are the precautions for Vue to implement the countdown button? The following is a practical case, let's take a look.
In project development, we often encounter buttons that send 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) } }Add two pieces of data to the data, one to record the time, and one to hold the specific content of the countdown button. In the countDown function, we use the setInterval timer to decrement the totalTime by 1 every second and change the content displayed in the button. The arrow function is used in window.setInterval because it will automatically bind the external this, so there is no need to save this first. The effect is as shown below:
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) },The above code solves the problem of 60 missing. At the same time, when totalTime is less than 0, it clears the synchronizer, resets the content in the button, and resets totalTime to 60 for next time use. The effect of counting down for 10 seconds:
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) }Add canClick in data. The default is true. If canClick is true, the code in countDown can be executed. If it is false, it will not work. Set canClick to false every time it is executed, and only change it to true when the countdown ends. This way the problem just now disappears.
<button class="button" :class="{disabled: !this.canClick}" @click="countDown"> ... .disabled{ background-color: #ddd; border-color: #ddd; color:#57a3f3; cursor: not-allowed; // 鼠标变化 }Effect:
Detailed explanation of the use of .sync modifier in vue
jQuery$. and $(). use Detailed explanation
The above is the detailed content of Vue implements countdown button. For more information, please follow other related articles on the PHP Chinese website!