uniapp倒计时
uniapp倒计时的实现方法
在uniapp中实现倒计时功能可以通过多种方式完成,以下是几种常见的方法:
使用setInterval实现基础倒计时
data() {
return {
count: 60, // 倒计时总秒数
timer: null
}
},
methods: {
startCountdown() {
this.timer = setInterval(() => {
if(this.count <= 0) {
clearInterval(this.timer)
return
}
this.count--
}, 1000)
}
},
onUnload() {
clearInterval(this.timer)
}
使用uniapp的uni-countdown组件
uniapp提供了内置的倒计时组件,可以直接使用:
<uni-countdown
:show-day="false"
:hour="1"
:minute="12"
:second="40"
@timeup="timeupHandler">
</uni-countdown>
使用第三方库如day.js
对于更复杂的倒计时需求,可以引入day.js等时间处理库:
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
dayjs.extend(duration)
// 计算剩余时间
const endTime = dayjs().add(1, 'hour')
const remaining = dayjs.duration(endTime.diff(dayjs()))
const hours = remaining.hours()
const minutes = remaining.minutes()
const seconds = remaining.seconds()
优化性能的requestAnimationFrame实现
对于需要精确到毫秒的倒计时,可以使用requestAnimationFrame:
data() {
return {
startTime: 0,
duration: 60000, // 60秒
remaining: 60000
}
},
methods: {
startCountdown() {
this.startTime = Date.now()
this.animateCountdown()
},
animateCountdown() {
const elapsed = Date.now() - this.startTime
this.remaining = Math.max(0, this.duration - elapsed)
if(this.remaining > 0) {
requestAnimationFrame(this.animateCountdown)
}
}
}
注意事项
- 组件销毁时务必清除定时器,避免内存泄漏
- 倒计时显示建议使用补零函数确保两位数显示
- 对于跨页面倒计时,可以考虑使用全局状态管理如vuex
- 服务端时间同步问题需要考虑时差校正
示例代码:完整倒计时组件
<template>
<view class="countdown">
{{ formatTime }}
</view>
</template>
<script>
export default {
data() {
return {
count: 60,
timer: null
}
},
computed: {
formatTime() {
const minutes = Math.floor(this.count / 60)
const seconds = this.count % 60
return `${minutes}:${seconds < 10 ? '0' + seconds : seconds}`
}
},
methods: {
start() {
this.timer = setInterval(() => {
if(this.count <= 0) {
clearInterval(this.timer)
this.$emit('end')
return
}
this.count--
}, 1000)
},
reset() {
clearInterval(this.timer)
this.count = 60
}
},
beforeDestroy() {
clearInterval(this.timer)
}
}
</script>






