Vue Js Countdown Timmer:Vue.js Countdown Timer is a component in Vue.js that enables the display of a timer or countdown clock on a web page. It can be used to create a sense of urgency or for time-sensitive applications. The component consists of a start time and an end time, and it updates in real-time based on the current time. It can also be customized with various styling and formatting options, and can be used to trigger events or functions upon reaching zero.
How can I implement a countdown timer using Vue js?
This is a Vue.js component that displays a countdown timer in the format of hours, minutes, and seconds. The timer starts at 5 hours (18000 seconds) and counts down by 1 second every second until it reaches 0, at which point the timer is stopped.
The component consists of a div with an ID of “app” that contains a div with a class of “timer”. Within the “timer” div, there are three spans with classes of “time” that display the hours, minutes, and seconds of the countdown.
The Vue.js component has a data property called “timeLeft” which is initialized to 18000 (5 hours in seconds). There are also three computed properties: “hours”, “minutes”, and “seconds” which calculate the hours, minutes, and seconds remaining in the countdown timer.
The Vue.js component has a mounted method that sets an interval that updates the “timeLeft” property every second, and stops the timer when “timeLeft” reaches 0. The component also has a beforeDestroy method that clears the interval to prevent any memory leaks when the component is destroyed.
Vue Js Countdown Timmer Example
<div id="app">
<div class="timer">
<span class="time">{{ hours }}</span> : <span class="time">{{ minutes }}</span> : <span class="time">{{seconds }}</span>
</div>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
timeLeft: 18000, // seconds (5 hours)
};
},
computed: {
hours() {
return Math.floor(this.timeLeft / 3600)
.toString()
.padStart(2, "0");
},
minutes() {
return Math.floor((this.timeLeft % 3600) / 60)
.toString()
.padStart(2, "0");
},
seconds() {
return (this.timeLeft % 60).toString().padStart(2, "0");
},
},
mounted() {
this.timer = setInterval(() => {
this.timeLeft--;
if (this.timeLeft === 0) {
clearInterval(this.timer);
// countdown finished
}
}, 1000);
},
beforeDestroy() {
clearInterval(this.timer);
},
})
</script>