效果展示
<template>
<view class="timedown">
支付倒计时:
<view class="shijian">{
{ countdownh }}</view>
<text>时</text>
<view class="shijian">{
{ countdownm }}</view>
<text>分</text>
<view class="shijian">{
{ countdowns }}</view>
<text>秒</text>
</view>
</template>
<script>
export default {
name: 'timedown',
data() {
return {
currenttime: '', //当前本机时间
countdownh: '', //小时
countdownm: '', //分钟
countdowns: '', //秒
timer: null //重复执行
};
},
props: {
// 传过来的截止时间
endtime: {
type: [Number, String],
default: 0
}
},
created() {
console.log(this.currenttime, '组件里面的时间');
this.timer = setInterval(() => {
this.currenttime = Math.floor(new Date().getTime() / 1000);
this.showtime();
}, 1000);
},
destroyed() {
console.log('组件销毁');
clearInterval(this.timer);
},
methods: {
showtime() {
// var nowtime = new Date(), //获取当前时间
// endtime = new Date('2021/12/10'); //定义结束时间
console.log(this.endtime - this.currenttime, '时间差值');
var lefttime = this.endtime - this.currenttime, //距离结束时间的毫秒数
leftd = Math.floor(lefttime / (60 * 60 * 24)), //计算天数
lefth =
Math.floor(((lefttime / (60 * 60)) % 24) + leftd * 24) < 10
? '0' + Math.floor(((lefttime / (60 * 60)) % 24) + leftd * 24)
: Math.floor(((lefttime / (60 * 60)) % 24) + leftd * 24), //计算小时数
leftm = Math.floor((lefttime / 60) % 60) < 10 ? '0' + Math.floor((lefttime / 60) % 60) : Math.floor((lefttime / 60) % 60), //计算分钟数
lefts = Math.floor(lefttime % 60) < 10 ? '0' + Math.floor(lefttime % 60) : Math.floor(lefttime % 60); //计算秒数
this.countdownh = lefth; //返回倒计时的字符串
this.countdownm = leftm; //返回倒计时的字符串
this.countdowns = lefts; //返回倒计时的字符串
// 倒计时结束时,显示00:00:00
if (lefttime < 0) {
this.countdownh = this.countdownm = this.countdowns = '00';
}
}
}
};
</script>
<style lang="scss" scoped>
.timedown {
font-size: 16rpx;
justify-content: space-between;
align-items: center;
display: flex;
margin-right: 16rpx;
.shijian {
font-size: 24rpx;
color: #e34d59;
}
}
</style>