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>
使用计算属性显示格式化时间
将秒数转换为 分钟:秒 的格式,提升可读性。

<template>
<div>{{ formattedTime }}</div>
</template>
<script>
export default {
computed: {
formattedTime() {
const minutes = Math.floor(this.countdown / 60)
const seconds = this.countdown % 60
return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`
}
}
// 其余代码与基础实现相同
}
</script>
使用 Vue 自定义指令封装
创建可复用的倒计时指令,适用于多个场景。
// 全局注册指令
Vue.directive('countdown', {
bind(el, binding) {
let count = binding.value || 60
const timer = setInterval(() => {
el.textContent = count
if (count-- <= 0) {
clearInterval(timer)
el.textContent = "时间到"
}
}, 1000)
el._countdownTimer = timer
},
unbind(el) {
clearInterval(el._countdownTimer)
}
})
// 使用方式
<div v-countdown="30"></div>
使用第三方库(如 moment.js)
处理更复杂的时间格式和时区问题。
import moment from 'moment'
methods: {
startCountdown() {
this.endTime = moment().add(60, 'seconds')
this.timer = setInterval(() => {
const diff = this.endTime.diff(moment(), 'seconds')
this.countdown = diff > 0 ? diff : 0
if (diff <= 0) clearInterval(this.timer)
}, 1000)
}
}
注意事项
- 组件销毁时务必清除定时器,避免内存泄漏
- 对于需要暂停/继续的场景,可扩展为存储剩余时间到
data - 服务端渲染(SSR)场景需注意
setInterval在服务端的兼容性 - 高精度需求可使用
requestAnimationFrame替代setInterval






