本文实例为大家分享了vue实现倒计时功能的具体代码,供大家参考,具体内容如下
通过父组件传入的结束时间减去当前日期得到剩余时间
1.子组件部分
1
2
3
|
< div class = "itemend" > < p class = "itemss" >倒计时< span >{{day}}</ span >天< span >{{hour}}</ span >时< span >{{minute}}</ span >分< span >{{second}}</ span >秒</ p > </ div > |
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
data() { return { day: "" , //天 hour: "" , //时 minute: "" , //分 second: "" , //秒 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; //天 this .hour = h; //时 this .minute = m; //分 this .second = s; //秒 }, formate(time) { if (time >= 10) { return time; } else { return `0${time}`; } }, } |
2.父组件引用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
< 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" //结束时间(苹果手机无法解析"-" 可以将格式改为2021/3/30) }, components: { Times, }, }; |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/youngKing0615/article/details/114672374