vue倒计时实现
Vue 倒计时实现方法
使用 setInterval 实现基础倒计时
在 Vue 组件中,可以通过 data 定义倒计时初始值,使用 setInterval 实现倒计时功能。
<template>
<div>{{ countdown }}</div>
</template>
<script>
export default {
data() {
return {
countdown: 60,
timer: null
}
},
mounted() {
this.startCountdown()
},
methods: {
startCountdown() {
this.timer = setInterval(() => {
if (this.countdown > 0) {
this.countdown--
} else {
clearInterval(this.timer)
}
}, 1000)
}
},
beforeDestroy() {
clearInterval(this.timer)
}
}
</script>
使用 computed 格式化显示时间
通过计算属性可以格式化倒计时显示,例如将秒数转换为分钟和秒。
computed: {
formattedTime() {
const minutes = Math.floor(this.countdown / 60)
const seconds = this.countdown % 60
return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`
}
}
使用 Vue 插件 vue-countdown
对于更复杂的倒计时需求,可以使用第三方库 vue-countdown。
安装:
npm install vue-countdown
使用示例:
<template>
<countdown :time="time" :interval="1000">
<template slot-scope="props">{{ props.minutes }}:{{ props.seconds }}</template>
</countdown>
</template>
<script>
import Countdown from 'vue-countdown'
export default {
components: { Countdown },
data() {
return {
time: 60 * 1000 // 60秒
}
}
}
</script>
带回调函数的倒计时实现
倒计时结束后可以触发回调函数执行特定操作。
methods: {
startCountdown() {
this.timer = setInterval(() => {
if (this.countdown > 0) {
this.countdown--
} else {
clearInterval(this.timer)
this.onCountdownEnd()
}
}, 1000)
},
onCountdownEnd() {
console.log('倒计时结束')
// 执行结束后的操作
}
}
使用 requestAnimationFrame 实现更精确倒计时
对于需要高精度计时的情况,可以使用 requestAnimationFrame。
methods: {
startHighPrecisionCountdown() {
const startTime = Date.now()
const duration = 60000 // 60秒
const updateCountdown = () => {
const elapsed = Date.now() - startTime
this.countdown = Math.max(0, Math.ceil((duration - elapsed) / 1000))
if (elapsed < duration) {
requestAnimationFrame(updateCountdown)
}
}
requestAnimationFrame(updateCountdown)
}
}






