uniapp倒计时
uniapp倒计时实现方法
使用setInterval实现基础倒计时
在uniapp中可以通过setInterval和clearInterval实现基础的倒计时功能。创建一个倒计时组件或页面方法:
data() {
return {
countdown: 60, // 倒计时秒数
timer: null
}
},
methods: {
startCountdown() {
this.timer = setInterval(() => {
if(this.countdown <= 0) {
clearInterval(this.timer)
return
}
this.countdown--
}, 1000)
}
},
onLoad() {
this.startCountdown()
},
onUnload() {
clearInterval(this.timer)
}
格式化显示时间
将秒数格式化为更友好的"分:秒"显示:
computed: {
formattedTime() {
const minutes = Math.floor(this.countdown / 60)
const seconds = this.countdown % 60
return `${minutes}:${seconds < 10 ? '0' + seconds : seconds}`
}
}
使用uniapp的countDown组件
uniapp的uView UI等组件库提供了现成的倒计时组件:
<u-count-down :timestamp="timestamp"></u-count-down>
优化性能的倒计时
使用requestAnimationFrame实现更精确的倒计时:
methods: {
startAnimationCountdown() {
let startTime = Date.now()
const duration = this.countdown * 1000
const animate = () => {
const elapsed = Date.now() - startTime
this.countdown = Math.ceil((duration - elapsed) / 1000)
if(elapsed < duration) {
requestAnimationFrame(animate)
}
}
requestAnimationFrame(animate)
}
}
跨页面倒计时管理
使用Vuex或globalData实现跨页面倒计时:
// main.js
Vue.prototype.$globalData = {
countdown: 60
}
// 页面中使用
this.$globalData.countdown
注意在组件销毁时清除定时器,避免内存泄漏。根据具体需求选择合适的实现方式,简单场景可使用基础setInterval,对精度要求高的场景建议使用requestAnimationFrame。







