vue实现倒计时
实现倒计时的基本方法
在Vue中实现倒计时功能,可以通过计算剩余时间并动态更新显示。以下是一个简单的实现方式:
<template>
<div>{{ formattedTime }}</div>
</template>
<script>
export default {
data() {
return {
countdown: 60, // 初始倒计时秒数
timer: null
}
},
computed: {
formattedTime() {
const minutes = Math.floor(this.countdown / 60)
const seconds = this.countdown % 60
return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`
}
},
mounted() {
this.timer = setInterval(() => {
if (this.countdown > 0) {
this.countdown--
} else {
clearInterval(this.timer)
}
}, 1000)
},
beforeDestroy() {
clearInterval(this.timer)
}
}
</script>
使用Vue Composition API实现
对于Vue 3或使用Composition API的项目,可以采用更简洁的方式:
<template>
<div>{{ minutes }}:{{ seconds < 10 ? '0' : '' }}{{ seconds }}</div>
</template>
<script>
import { ref, computed, onMounted, onUnmounted } from 'vue'
export default {
setup() {
const countdown = ref(60)
const timer = ref(null)
const minutes = computed(() => Math.floor(countdown.value / 60))
const seconds = computed(() => countdown.value % 60)
onMounted(() => {
timer.value = setInterval(() => {
if (countdown.value > 0) {
countdown.value--
} else {
clearInterval(timer.value)
}
}, 1000)
})
onUnmounted(() => {
clearInterval(timer.value)
})
return { minutes, seconds }
}
}
</script>
带回调函数的倒计时组件
可以创建一个可复用的倒计时组件,支持完成回调:
<template>
<div>{{ timeText }}</div>
</template>
<script>
export default {
props: {
duration: {
type: Number,
default: 60
},
onFinish: {
type: Function,
default: () => {}
}
},
data() {
return {
remaining: this.duration
}
},
computed: {
timeText() {
const mins = Math.floor(this.remaining / 60)
const secs = this.remaining % 60
return `${mins}:${secs < 10 ? '0' : ''}${secs}`
}
},
mounted() {
this.startCountdown()
},
methods: {
startCountdown() {
this.timer = setInterval(() => {
this.remaining--
if (this.remaining <= 0) {
clearInterval(this.timer)
this.onFinish()
}
}, 1000)
}
},
beforeDestroy() {
clearInterval(this.timer)
}
}
</script>
使用第三方库
对于更复杂的倒计时需求,可以考虑使用专门的库如vue-countdown:
<template>
<countdown :time="time" :interval="100" tag="p">
<template slot-scope="props">{{ props.minutes }}:{{ props.seconds }}.{{ props.milliseconds }}</template>
</countdown>
</template>
<script>
import Countdown from 'vue-countdown'
export default {
components: { Countdown },
data() {
return {
time: 60 * 1000 // 60秒
}
}
}
</script>
注意事项
实现倒计时功能时需要注意内存管理,确保在组件销毁时清除定时器。倒计时精度取决于JavaScript事件循环,对于高精度需求可能需要特殊处理。跨标签页时,浏览器可能会降低定时器精度以节省资源。







