Vue Countdown Timer Component
Sun, 21 Oct 2018
At the end of this post you'll learn how to implement a basic vue countdown timer component.
In a web project I built I needed to show the user a countdown timer until the UI/options will expire.
So I ended up building a quite simple Vue Component that can be integrated in any app and that can be easily extended for any needs.
The template of the Vue Countdown Timer Component looks like this.
I've also used Bootstrap class to make the timer red when there's no more time left.
<template> <div> <p :class="{'text-danger': total<=0}"> <strong>{{minutes}}</strong> <strong>:</strong> <strong>{{seconds}}</strong> </p> </div> </template>
The controller of the component:
export default { props: { time: { type: Number, default: 0 } }, data: function () { return { total: '', minutes: '--', seconds: '--', interval: 0 } }, mounted: function () { this.total = parseInt(this.time, 10) this.interval = setInterval(() => { this.tick() }, 1000) }, methods: { str_pad_left: function (string, pad, length) { return (new Array(length+1).join(pad)+string).slice(-length) }, tick: function () { var minutes = Math.floor(this.total / 60) var seconds = this.total - minutes * 60 this.minutes = this.str_pad_left(minutes, '0', 2) this.seconds = this.str_pad_left(seconds, '0', 2)
if (this.total <= 0) {
clearInterval(this.interval)
this.$bus.$emit('Timer/stop')
}
this.total -= 1
}
}
}
What it does: The props defines which parameter to receive from the parent component. In our case it represents the number of seconds that the timer will start from.
The data contains properties required for showing the current state of the timer and for allowing us to control the interval handler.
When mounted, the component reads the time parameter and initializes the interval at which it will update the progress.
Tick method is executed as defined in the mounted interval. It will generate pretty minutes and seconds padded with '0'.
When the total seconds get to 0 we'll also $emit an event. See my previous post for learning how to implement Observer Pattern in Vue.
Integrating the timer in our app is as easy as:
<Timer :time="300" />
That's all. Our Vue countdown timer components is ready.
Categories: how-to, javascript, vuejs