Vue - Setting up a countdown timer in Vue
Countdown timers are a very common feature in modern web applications. In Vue, we can easily implement a countdown timer to provide feedback to users when they perform certain actions.
In this article, we'll look at how to set up a countdown timer in Vue, with some example code and best practices.
Use Vue's computed properties to calculate the countdown
Computed properties in Vue are a very useful feature that can calculate a value based on the current state. In the countdown timer, we can use computed properties to calculate the current remaining time.
First, we need to define a countdown end time. In this example, we will use JavaScript's Date object to represent the end time:
data() {
return {
endTime: new Date('2021-12-31T23:59:59')
}
}
We can then create a computed property to calculate the current remaining time:
computed: {
remainingTime() {
let now = new Date()
let diff = this.endTime - now
let seconds = Math.floor(diff / 1000)
let minutes = Math.floor(seconds / 60)
let hours = Math.floor(minutes / 60)
let days = Math.floor(hours / 24)
return {
seconds: seconds % 60,
minutes: minutes % 60,
hours: hours % 24,
days: days
}
}
}
In this computed property, we first get the current time and then calculate the difference between the end time and the current time. Next, we convert the difference into seconds, minutes, hours, and days and store them in an object to use later in the template.
Display countdown in template
Now that we have defined a computed property to calculate the remaining time, we can use it in our template to display the countdown.
<template>
<div>
<span>{{ remainingTime.days }} days </span>
<span>{{ remainingTime.hours }} hours </span>
<span>{{ remainingTime.minutes }} minutes </span>
<span>{{ remainingTime.seconds }} seconds </span>
</div>
</template>
In this template, we use mustache
the syntax to display the remaining time stored in the computed property. We display the remaining days, remaining hours, remaining minutes, and remaining seconds in different span elements.
Add dynamic updates
Now, we have been able to set up a countdown timer in Vue and display it in the template. However, this countdown timer will only calculate the remaining time once when the page loads. In order to make the countdown timer dynamically update, we need to use Vue's lifecycle hook function.
Specifically, we can use the mounted hook function to start a timer that updates the remaining time stored in the computed property every second.
mounted() {
this.timer = setInterval(() => {
this.remainingTime = this.calculateRemainingTime()
}, 1000)
}
In this code, we use the setInterval function to start a timer that executes every second. Each time the timer function executes, we recalculate the remaining time and store it in a computed property.
Best Practices
When setting up a countdown timer in Vue, there are some best practices that can help us write better code. Here are some things to keep in mind:
- Add get and set methods for the computed property so that you can manually set the remaining time when needed.
- Use a relative time library such as moment.js to calculate time differences to make it easier to handle different time zones and daylight saving time.
- Clear the timer when the component is destroyed to avoid memory leaks.
Sample Code
Finally, here is a complete Vue component that implements a countdown timer and displays it in a template:
<template>
<div>
<span>{{ remainingTime.days }} days </span>
<span>{{ remainingTime.hours }} hours </span>
<span>{{ remainingTime.minutes }} minutes </span>
<span>{{ remainingTime.seconds }} seconds </span>
</div>
</template>
<script>
import moment from 'moment'
export default {
data() {
return {
endTime: new Date('2021-12-31T23:59:59')
}
},
computed: {
remainingTime: {
get() {
let now = new Date()
let diff = this.endTime - now
let duration = moment.duration(diff)
return {
seconds: duration.seconds(),
minutes: duration.minutes(),
hours: duration.hours(),
days: duration.days()
}
},
set(value) {
this.endTime = value
}
}
},
mounted() {
this.timer = setInterval(() => {
this.remainingTime = this.calculateRemainingTime()
}, 1000)
},
beforeDestroy() {
clearInterval(this.timer)
},
methods: {
calculateRemainingTime() {
let now = new Date()
let diff = this.endTime - now
let duration = moment.duration(diff)
return {
seconds: duration.seconds(),
minutes: duration.minutes(),
hours: duration.hours(),
days: duration.days()
}
}
}
}
</script>
In this component, we use the moment.js library to calculate time differences and add the get
and set
methods to computed properties. We also mounted
start a timer in the hook function and beforeDestroy
clear it in the hook function.
Summarize
In this article, we introduced how to set up a countdown timer in Vue, and provided some sample code and best practices. By using Vue's computed properties and lifecycle hook functions, we can easily implement a dynamically updated countdown timer and display it in the template.
In actual development, countdown timer is a very common function that can be used in various scenarios, such as user login timeout, verification code validity period, countdown for flash sale activities, etc. By mastering the method of setting countdown timer in Vue, we can provide these functions to users more easily.
Of course, in addition to the methods mentioned in this article, there are many other implementation methods and techniques. In the actual development process, we can choose the most suitable method to implement the countdown timer according to specific needs and project characteristics.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Configuring Apache Web Server on Ubuntu and Debian
Publish Date:2025/04/05 Views:176 Category:OPERATING SYSTEM
-
This article shows you how to install Apache web server on Ubuntu and Debian, set it up, and access the access logs. Apache Web Server in Ubuntu and Debian Apache HTTP Server is a free and open source web server that is very popular. More t
How to use Docker to image a Node.js web application
Publish Date:2025/03/26 Views:107 Category:Docker
-
Docker is a containerization platform that simplifies the packaging and execution of applications. Containers run as independent processes with their own file systems, but share the kernel of their host machine. Docker has attracted much at
My understanding of webservice is this
Publish Date:2025/03/18 Views:150 Category:NETWORK
-
Recently, I encountered such a project at work (temporarily named Project A). Project A itself was developed in PHP, but its data came from another project developed in Java (temporarily named Project B). Project A could not operate the dat
Which technology do you choose to implement the web chat room?
Publish Date:2025/03/18 Views:62 Category:NETWORK
-
With the rise of HTML5 Websockets, web chat applications are becoming more and more popular. Recently, I am working on a mobile web application, the core function of which is to implement web chat on the mobile phone. Of course, the functio
How to redirect a website from HTTP to HTTPS
Publish Date:2025/03/16 Views:117 Category:NETWORK
-
HTTPS is a protocol for secure communication over computer networks and is widely used on the Internet. More and more website owners are migrating from HTTP to HTTPS, mainly due to the following 5 reasons: Google announced that websites usi
How to avoid soft 404 in the website during SEO
Publish Date:2025/03/17 Views:136 Category:NETWORK
-
This article shares an SEO problem, soft 404. A status code we often see on websites is 404. Whether we develop a website or not, this is a problem we have to face. What is a soft 404? Before talking about soft 404, we must first understand
Performance differences between HTTP REST API and WebSocket REST API
Publish Date:2025/03/17 Views:161 Category:NETWORK
-
What is a REST API? REST or RESTful API design (Representational State Transfer) is an architectural style that uses existing protocols. There are six key constraints for REST API design:
Webpack packages ES6 and CommonJs mixed React
Publish Date:2025/03/02 Views:179 Category:React
-
This article mainly introduces how to use webpack to package and compile React mixed with ES6 and CommonJs. It is a process of upgrading the React environment.
Details that need to be paid attention to when compiling react with webpack
Publish Date:2025/03/02 Views:201 Category:React
-
It is very convenient to compile and package react using webpack. Both need to be installed using npm. However, if you do not pay attention to the installation location of webpack and react parser babel during use, problems will occur during