1.效果展示
2.思路需要后端返回一个结束的时间戳(注意是毫秒时间戳,如果是秒需要在后面加3个0转为毫秒),获取当当前时间戳,当前时间戳减去商品结束的时间戳得出要倒计时的时间戳,然后再进行值得处理
3.代码展示
<template>
<view>
<u-count-down @finish='finish' ref="countDown" :time="times" format="DD:HH:mm:ss"
autoStart millisecond @change="onChange">
<view class="time1">
<view class="time__item">{{ timeData.days }} </view>
<view class="time__doc">:</view>
<view class="time__item">
{{ timeData.hours>10?timeData.hours:'0'+timeData.hours}}
</view>
<view class="time__doc">:</view>
<view class="time__item">{{ timeData.minutes }} </view>
<view class="time__doc">:</view>
<view class="time__item">{{ timeData.seconds }} </view>
</view>
</u-count-down>
</view>
</template>
<style lang="scss">
// 时间
.time1 {
@include flex;
align-items: center;
&__item {
color: #F14747;
font-size: 24rpx;
text-align: center;
}
.time__item {
background-color: #EC9D20;
color: #fff;
width: 40rpx;
height: 40rpx;
display: flex;
align-items: center;
justify-content: center;
font-size: 24rpx;
}
.time__doc {
padding: 0 7rpx;
color: #fff;
}
}
</style>
<script>
import utils from '@/utils/index.js'
export default {
data() {
return {
times: null,
timeData: {},
kanjianinfo:{}
}
},
onLoad(){
this.uodate()
},
beforeDestroy() {
this.$refs.countDown.reset();//页面销毁重置定时器,避免进入其他页面依旧再倒计时,影响小程序性能
console.log('页面隐藏了')
},
methods:{
//倒计时结束
finish() {
console.log('结束');
},
onChange(e) {
this.timeData = e
},
//从后端拿到请求数据
uodate(){
//模拟数据
//
this.kanjianinfo.endtime = 1669824000000;//2022-12-01 00:00:00
this.downTime()
},
// 倒计时
downTime() {
//获取当前时间戳
let newDate = Date.now();
let chaTime = null;
//if (this.kanjianinfo.status == 'ing') {
// chaTime = this.kanjianinfo.endtime * 1000;//后端返秒*1000转为毫秒
//} else if (this.kanjianinfo.status == 'waiting') {
// chaTime = this.kanjianinfo.starttime * 1000;
// }
chaTime = this.kanjianinfo.endtime
this.times = chaTime - newDate;
console.log('倒计时开始', chaTime, ';', this.times);
this.timeData = {
days: this.toHHmmss(this.times)[0],
hours: this.toHHmmss(this.times)[1],
minutes: this.toHHmmss(this.times)[2],
seconds: this.toHHmmss(this.times)[3] * 1,
}
this.$forceUpdate()
},
//倒计时
toHHmmss(inputTime) {
var dec = inputTime / 1000;
//得到天 格式化成前缀加零的样式
var d = parseInt(dec / 60 / 60 / 24);
d = d < 10 ? '0' + d : d;
//得到小时 格式化成前缀加零的样式
var h = parseInt(dec / 60 / 60 % 24);
h = h < 10 ? '0' + h : h;
//得到分钟 格式化成前缀加零的样式
var m = parseInt(dec / 60 % 60);
m = m < 10 ? '0' + m : m;
//得到秒 格式化成前缀加零的样式
var s = parseInt(dec % 60);
s = s < 10 ? '0' + s : s;
return [d, h, m, s]
},
}
}
</script>