uniapp倒计时组件
uniapp倒计时组件实现方法
使用内置组件实现
uniapp本身没有专门的倒计时组件,但可以通过<text>或<view>结合定时器实现基础功能。
<template>
<view>
<text>{{countdown}}</text>
</view>
</template>
<script>
export default {
data() {
return {
countdown: '00:00:00',
timer: null,
totalSeconds: 3600 // 1小时倒计时
}
},
mounted() {
this.startCountdown()
},
methods: {
startCountdown() {
this.timer = setInterval(() => {
if(this.totalSeconds <= 0) {
clearInterval(this.timer)
return
}
this.totalSeconds--
this.formatTime()
}, 1000)
},
formatTime() {
const hours = Math.floor(this.totalSeconds / 3600)
const minutes = Math.floor((this.totalSeconds % 3600) / 60)
const seconds = this.totalSeconds % 60
this.countdown = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}
},
beforeDestroy() {
clearInterval(this.timer)
}
}
</script>
使用第三方插件
uni-ui提供了uni-countdown组件,可以直接使用:
<template>
<view>
<uni-countdown
:show-day="false"
:hour="1"
:minute="0"
:second="0"
@timeup="timeup">
</uni-countdown>
</view>
</template>
<script>
import uniCountdown from '@/components/uni-countdown/uni-countdown.vue'
export default {
components: {uniCountdown},
methods: {
timeup() {
uni.showToast({
title: '倒计时结束',
icon: 'none'
})
}
}
}
</script>
自定义高级倒计时组件
创建更灵活的倒计时组件,支持多种格式和回调:
<template>
<view class="countdown-container">
<text v-if="showDay">{{days}}天</text>
<text>{{hours}}</text>
<text>:</text>
<text>{{minutes}}</text>
<text>:</text>
<text>{{seconds}}</text>
</view>
</template>
<script>
export default {
props: {
endTime: {
type: [String, Number],
required: true
},
showDay: {
type: Boolean,
default: true
}
},
data() {
return {
days: '00',
hours: '00',
minutes: '00',
seconds: '00',
timer: null
}
},
mounted() {
this.startCountdown()
},
methods: {
startCountdown() {
this.timer = setInterval(() => {
const now = new Date().getTime()
const end = new Date(this.endTime).getTime()
const distance = end - now
if (distance < 0) {
clearInterval(this.timer)
this.$emit('timeup')
return
}
this.days = Math.floor(distance / (1000 * 60 * 60 * 24)).toString().padStart(2, '0')
this.hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString().padStart(2, '0')
this.minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)).toString().padStart(2, '0')
this.seconds = Math.floor((distance % (1000 * 60)) / 1000).toString().padStart(2, '0')
}, 1000)
}
},
beforeDestroy() {
clearInterval(this.timer)
}
}
</script>
<style>
.countdown-container {
display: flex;
align-items: center;
}
</style>
注意事项
定时器需要在组件销毁时清除,避免内存泄漏。倒计时精度受系统性能影响,长时间运行的倒计时建议定期与服务器时间同步。对于需要极高精度的场景,可以使用WebSocket实时同步时间。
移动端页面进入后台时定时器可能被暂停,重新进入前台时需要检查时间差并更新倒计时状态。跨平台开发时注意不同平台的定时器行为差异。






