Home Web Front-end JS Tutorial Vue makes countdown button effect

Vue makes countdown button effect

Jun 07, 2018 am 10:38 AM
vue

This time I will bring you the effect of making a countdown button with Vue. What are the precautions for making the effect of the countdown button with Vue? Here 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:

In order to show the effect faster, I set the time to 5 seconds. After clicking the button, a countdown will appear. At the same time, the button will become unclickable, its style will also change, and the appearance of the mouse hovering will also change.

Next we use code to implement it:

<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)
  }
}
Copy after login

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:

But there are still some problems with this button:

After clicking the button, after 1 second, it will go directly from The countdown starts at 59 seconds, and the 60 in the middle is gone.
You can still click during the countdown.
The countdown has not been cleared yet.

Next, you need to continue to improve the countDown function to solve these problems.

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 = &#39;重新发送验证码&#39;
    this.totalTime = 60
    }
 },1000)
},
Copy after login

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:

Found a bug. After clicking multiple times, the speed of rewinding becomes faster. This is because each click will Start a setInterval, these setIntervals will reduce totalTime. The solution is also very simple: simply throttle it, that is, make the code of the countDonw function non-executable after the first click of the button, and wait until the countdown is over before it can be executed again.

data () {
  return {
   content: &#39;发送验证码&#39;,
   totalTime: 10,
   canClick: true //添加canClick
  }
}
...
countDown () {
 if (!this.canClick) return  //改动的是这两行代码
 this.canClick = false
 this.content = this.totalTime + &#39;s后重新发送&#39;
 let clock = window.setInterval(() => {
  this.totalTime--
  this.content = this.totalTime + 's后重新发送'
  if (this.totalTime < 0) {
   window.clearInterval(clock)
   this.content = &#39;重新发送验证码&#39;
   this.totalTime = 10
   this.canClick = true  //这里重新开启
  }
 },1000)
}
Copy after login

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.

It’s almost done here, but you can also adjust the style:

<button class="button" :class="{disabled: !this.canClick}" @click="countDown">
...
.disabled{
 background-color: #ddd;
 border-color: #ddd;
 color:#57a3f3;
 cursor: not-allowed; // 鼠标变化
}
Copy after login

Effect:

This countdown button is very simple, but it was still very messy when I first wrote it, and I didn’t know the concept of function throttling at that time.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

vue.js element-ui makes a menu tree structure

How to use JS to obtain users City and geographical location

The above is the detailed content of Vue makes countdown button effect. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to query the version of vue How to query the version of vue Apr 07, 2025 pm 11:24 PM

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the &lt;script&gt; tag in the HTML file that refers to the Vue file.

How to use function intercept vue How to use function intercept vue Apr 08, 2025 am 06:51 AM

Function interception in Vue is a technique used to limit the number of times a function is called within a specified time period and prevent performance problems. The implementation method is: import the lodash library: import { debounce } from 'lodash'; Use the debounce function to create an intercept function: const debouncedFunction = debounce(() =&gt; { / Logical / }, 500); Call the intercept function, and the control function is called at most once in 500 milliseconds.

See all articles