vue realizes countdown function
- 2021-11-01 02:20:11
- OfStack
In this paper, we share the specific code of vue to realize countdown function for your reference. The specific contents are as follows
The end time passed in by the parent component is subtracted from the current date to obtain the remaining time
1. Subcomponent section
<div class="itemend">
<p class="itemss"> Countdown <span>{{day}}</span> Days <span>{{hour}}</span> Hour <span>{{minute}}</span> Points <span>{{second}}</span> Seconds </p>
</div>
Code:
data() {
return {
day: "", // Days
hour: "", // Hour
minute: "", // Points
second: "", // Seconds
flag: false,
};
},
mounted() {
let time = setInterval(() => {
if (this.flag == true) {
clearInterval(time);
}
this.timeDown();
}, 500);
},
props: {
endTime: {
type: String,
},
},
methods: {
timeDown() {
const endTime = new Date(this.endTime);
const nowTime = new Date();
let leftTime = parseInt((endTime.getTime() - nowTime.getTime()) / 1000);
let d = parseInt(leftTime / (24 * 60 * 60));
let h = this.formate(parseInt((leftTime / (60 * 60)) % 24));
let m = this.formate(parseInt((leftTime / 60) % 60));
let s = this.formate(parseInt(leftTime % 60));
if (leftTime <= 0) {
this.flag = true;
this.$emit("time-end");
}
this.day = d; // Days
this.hour = h; // Hour
this.minute = m; // Points
this.second = s; // Seconds
},
formate(time) {
if (time >= 10) {
return time;
} else {
return `0${time}`;
}
},
}
2. Parent component reference
<template>
<div>
<Times :endTime='timeEnd'></Times>
</div>
</template>
import Times from "@/components/time";
export default {
name: "Home",
data() {
return {
timeEnd: "2021-3-30 9:50" // End time ( Apple phone can't be parsed "-" You can change the format to 2021/3/30)
},
components: {
Times,
},
};
For more articles about countdown, please see the special topic: "Countdown Function"
More JavaScript clock effects click to view: JavaScript clock effects topic