uniapp倒计时功能
需求
挂号以后,通过接口获取下单时间,约定9分钟后过期,将倒计时显示在页面上
实现
代码:
js
// 计算倒计时
calculateCountdown() {
if (!this.apointTime) {
return
}
const apointTime = new Date(this.apointTime.replace(/-/g, '/'))
// 到期时间
apointTime.setMinutes(apointTime.getMinutes() + 9)
const expirationTime = apointTime.getTime()
// 当前时间
const currentTime = new Date().getTime()
const remainder = expirationTime - currentTime > 0 ? expirationTime - currentTime : 0
if (remainder > 0) {
this.ifExpires = false
this.showCountDown = false
let seconds = Math.floor(remainder / 1000)
this.countdownMinute = Math.floor(seconds / 60)
this.countdownSecond = Math.floor(seconds % 60)
this.$nextTick(() => {
this.showCountDown = true
})
} else {
this.ifExpires = true
}
}
一、通过调用接口,获取下单时间,保存到apointTime中
二、对到期时间进行处理
1、转换连接符,因为ios环境部识别-,必须改成/
js
const apointTime = new Date(this.apointTime.replace(/-/g, '/'))
2、通过setMinutes()方法,给下单时间添加9分钟,生成到期时间,再调用getTime()方法,转换成对应的时间戳
js
// 到期时间
apointTime.setMinutes(apointTime.getMinutes() + 9)
const expirationTime = apointTime.getTime()
3、获取当前时间的时间戳
js
// 当前时间
const currentTime = new Date().getTime()
4、计算俩个时间的差额
js
const remainder = expirationTime - currentTime > 0 ? expirationTime - currentTime : 0
5、通过差额,获取对应的分和秒
js
let seconds = Math.floor(remainder / 1000)
this.countdownMinute = Math.floor(seconds / 60)
this.countdownSecond = Math.floor(seconds % 60)
三、引入uniapp的uni-countdown倒计时组件
html
<uni-countdown v-if="showCountDown" color="#FFA177" :show-day="false" :show-hour="false" :minute="countdownMinute" :second="countdownSecond" @timeup="timeup"/>
备注
在测试的时候发现,ios环境下,有时候分秒值都改了,但uni-countdown显示的还是之前的
解决办法:在uni-countdown组件上加上v-if,在计算计算倒计时方法里给showCountDown赋值