vue实现倒计时
Vue 实现倒计时的常见方法
使用 setInterval 实现基础倒计时
在 Vue 组件的 data 中定义倒计时相关变量:
data() {
return {
countdown: 60, // 初始倒计时秒数
timer: null // 存储定时器
}
}
在方法中启动倒计时:
methods: {
startCountdown() {
this.timer = setInterval(() => {
if (this.countdown > 0) {
this.countdown--
} else {
clearInterval(this.timer)
}
}, 1000)
}
}
在模板中显示倒计时:
<template>
<button @click="startCountdown" :disabled="countdown !== 60">
{{ countdown === 60 ? '获取验证码' : `${countdown}秒后重试` }}
</button>
</template>
使用 computed 计算格式化时间
对于需要显示分钟和秒的倒计时:
computed: {
formattedTime() {
const minutes = Math.floor(this.countdown / 60)
const seconds = this.countdown % 60
return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`
}
}
使用 Vue 生命周期管理定时器
在组件销毁时清除定时器:
beforeDestroy() {
clearInterval(this.timer)
}
使用第三方库实现更复杂倒计时
安装 vue-countdown 插件:
npm install vue-countdown
在组件中使用:
import VueCountdown from '@xkeshi/vue-countdown'
export default {
components: {
VueCountdown
}
}
模板中使用:
<vue-countdown
:time="60 * 1000"
v-slot="{ minutes, seconds }">
剩余时间:{{ minutes }}分{{ seconds }}秒
</vue-countdown>
使用 Date 对象实现精确倒计时
避免 setInterval 的误差:
methods: {
preciseCountdown(endTime) {
const now = new Date().getTime()
const distance = endTime - now
if (distance <= 0) {
return clearInterval(this.timer)
}
this.countdown = Math.floor(distance / 1000)
}
}
使用 CSS 动画增强视觉效果
为倒计时添加动画效果:
<transition name="fade">
<span v-show="countdown > 0" class="countdown-text">
{{ countdown }}
</span>
</transition>
CSS 样式:
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
.countdown-text {
font-size: 24px;
color: #ff5722;
}






