vue实现倒计时功能
时间:2023-02-24 09:16:30|栏目:vue|点击: 次
本文实例为大家分享了vue实现倒计时功能的具体代码,供大家参考,具体内容如下
通过父组件传入的结束时间减去当前日期得到剩余时间
1.子组件部分
<div class="itemend"> <p class="itemss">倒计时<span>{{day}}</span>天<span>{{hour}}</span>时<span>{{minute}}</span>分<span>{{second}}</span>秒</p> </div>
代码:
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.父组件引用
<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, }, };
更多关于倒计时的文章请查看专题:《倒计时功能》
更多JavaScript时钟特效点击查看:JavaScript时钟特效专题