<template>
<div class="count-down-wrapper">
<template v-if="endingDesc != ''">{{ endingDesc }}</template>
<template v-else>
<p :style="countStyle">{{ leftTime.day }}</p>
<span :style="spanStyle">天</span>
<p :style="countStyle">{{ leftTime.hour }}</p>
<span :style="spanStyle">小时</span>
<p :style="countStyle">{{ leftTime.min }}</p>
<span :style="spanStyle">分</span>
<p :style="countStyle">{{ leftTime.sec }}</p>
<span :style="spanStyle">秒</span>
</template>
</div>
</template>
<script>
export default {
name: "CountDown",
props: {
// 结束时间戳
endTimeStamp: {
type: Number,
// todo-删除
default: 1642225898000,
},
// 数字样式
countStyle: {
type: String,
default:
"display: inline-block;font-size: 20px;font-family: DIN-BoldItalic, DIN;font-weight: bold;color: #333333;line-height: 24px;font-style:italic",
},
// 时分秒秒样式
spanStyle: {
type: String,
default: "font-size: 14px; font-weight: 400; color: #1B1B1B;",
},
// 是否需要倒计时
needCount: {
type: Boolean,
default: true,
},
},
data() {
return {
leftTime: {
day: "",
hour: "",
min: "",
sec: "",
},
endingDesc: "", // 标识倒计时结束
};
},
mounted() {
const EndTime = this.endTimeStamp; //结束时间
const NowTimeStamp = new Date().valueOf();
if (EndTime <= NowTimeStamp) {
// 倒计时
this.endingDesc = "计时结束";
return;
}
const _this = this;
if (this.needCount) {
setInterval(function () {
_this.getRTime();
}, 1000);
} else {
_this.getRTime();
}
},
methods: {
addZero(num) {
return num < 10 ? "0" + num : num;
},
getRTime() {
const EndTime = this.endTimeStamp; //结束时间
const NowTimeStamp = new Date().valueOf();
if (EndTime <= NowTimeStamp) {
// 倒计时
this.endingDesc = "计时结束";
return;
}
const NowTime = new Date(); //当前时间
//后台给我的是10位 精确到秒的 所有下面我就除以了1000,不要小数点后面的
// var t = EndTime - (NowTime.getTime() / 1000).toFixed(0);
const t = EndTime - NowTime.getTime().toFixed(0);
//如果后台给的是毫秒 上面不用除以1000 下面的计算时间也都要除以1000 这里我去掉1000了
let d = Math.floor(t / 1000 / 60 / 60 / 24); //天 var d=Math.floor(t/1000/60/60/24)
let h = Math.floor((t / 1000 / 60 / 60) % 24); //时 var h=Math.floor(t/1000/60/60%24)
let m = Math.floor((t / 1000 / 60) % 60); //分 var m=Math.floor(t/1000/60%60)
let s = Math.floor((t / 1000) % 60); //秒 var s=Math.floor(t/1000%60)
d = this.addZero(parseInt(d));
h = this.addZero(parseInt(h));
m = this.addZero(parseInt(m));
s = this.addZero(parseInt(s));
this.leftTime.day = d;
this.leftTime.hour = h;
this.leftTime.min = m;
this.leftTime.sec = s;
},
},
};
</script>
<style lang="less" scoped>
.count-down-wrapper {
p {
display: inline-block;
}
span {
display: inline-block;
}
}
</style>
倒计时组件
最新推荐文章于 2024-07-01 15:44:31 发布