Posted in Vue.js onMarch 24, 2021
通过父组件传入的结束时间减去当前日期得到剩余时间
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,
},
};
vue实现倒计时功能
- Author -
程序猿余某人声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@