Last active
May 3, 2024 13:22
-
-
Save davision/3a364a3c3a25a89457dfdc346a7da0a1 to your computer and use it in GitHub Desktop.
Simple countdown component for VueJS 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template lang="html"> | |
<div v-if="isEnded"> | |
Ended. | |
</div> | |
<div v-else> | |
<div>Days: {{ days }}</div> | |
<div>Hours: {{ hours }}</div> | |
<div>Minutes: {{ minutes }}</div> | |
<div>Seconds: {{ seconds }}</div> | |
</div> | |
</template> | |
<script> | |
export default { | |
props: { | |
endDate: { | |
type: Date // Date.parse(this.endDate) | |
} | |
}, | |
data () { | |
return { | |
days: null, | |
hours: null, | |
minutes: null, | |
seconds: null, | |
isEnded: null | |
} | |
}, | |
methods: { | |
updateRemaining (distance) { | |
this.days = Math.floor(distance / (1000 * 60 * 60 * 24)) | |
this.hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) | |
this.minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)) | |
this.seconds = Math.floor((distance % (1000 * 60)) / 1000) | |
}, | |
tick () { | |
const currentTime = new Date() | |
const distance = Math.max(this.endDate - currentTime, 0) | |
this.updateRemaining(distance) | |
if (distance === 0) { | |
clearInterval(this.timer) | |
this.isEnded = true | |
} | |
} | |
}, | |
mounted () { | |
this.tick() | |
this.timer = setInterval(this.tick.bind(this), 1000) | |
}, | |
destroy () { | |
clearInterval(this.timer) | |
} | |
} | |
</script> | |
// Special thanks to Goran Kordun for his help |
You're welcome! 👍
Thanks! Simple and useful.
Can I get an example of a set end date? Now it gives me NaN
in the date.
Thanks
Can I get an example of a set end date? Now it gives me
NaN
in the date.Thanks
Same question here.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, just what I need to know.