vue实现倒计时功能
使用 Vue 实现倒计时功能
方法一:基于 setInterval 的简单倒计时
在 Vue 组件的 data 中定义倒计时初始值,并通过 setInterval 每秒更新剩余时间。
<template>
<div>{{ formattedTime }}</div>
</template>
<script>
export default {
data() {
return {
seconds: 60, // 倒计时总秒数
timer: null
};
},
computed: {
formattedTime() {
const mins = Math.floor(this.seconds / 60);
const secs = this.seconds % 60;
return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
}
},
mounted() {
this.timer = setInterval(() => {
if (this.seconds > 0) {
this.seconds--;
} else {
clearInterval(this.timer);
}
}, 1000);
},
beforeDestroy() {
clearInterval(this.timer);
}
};
</script>
方法二:封装可复用的倒计时组件
将倒计时逻辑封装为独立组件,支持通过 props 传入初始时间。
<template>
<div>{{ formattedTime }}</div>
</template>
<script>
export default {
props: {
initialSeconds: {
type: Number,
default: 60
}
},
data() {
return {
seconds: this.initialSeconds,
timer: null
};
},
computed: {
formattedTime() {
const mins = Math.floor(this.seconds / 60);
const secs = this.seconds % 60;
return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
}
},
mounted() {
this.startTimer();
},
methods: {
startTimer() {
this.timer = setInterval(() => {
if (this.seconds > 0) {
this.seconds--;
} else {
clearInterval(this.timer);
this.$emit('timeup');
}
}, 1000);
}
},
beforeDestroy() {
clearInterval(this.timer);
}
};
</script>
方法三:使用 requestAnimationFrame 实现高精度倒计时
适用于需要更高精度的场景(如动画同步)。
<template>
<div>{{ formattedTime }}</div>
</template>
<script>
export default {
data() {
return {
endTime: Date.now() + 60000, // 1分钟后结束
remainingTime: 60000,
animationFrame: null
};
},
computed: {
formattedTime() {
const secs = Math.ceil(this.remainingTime / 1000);
const mins = Math.floor(secs / 60);
const remainingSecs = secs % 60;
return `${mins}:${remainingSecs < 10 ? '0' : ''}${remainingSecs}`;
}
},
mounted() {
this.updateTime();
},
methods: {
updateTime() {
this.remainingTime = this.endTime - Date.now();
if (this.remainingTime > 0) {
this.animationFrame = requestAnimationFrame(this.updateTime);
} else {
this.remainingTime = 0;
}
}
},
beforeDestroy() {
cancelAnimationFrame(this.animationFrame);
}
};
</script>
方法四:结合 Vuex 管理全局倒计时状态
适用于需要跨组件共享倒计时状态的场景。
// store.js
export default new Vuex.Store({
state: {
countdown: 60
},
mutations: {
decrementCountdown(state) {
if (state.countdown > 0) state.countdown--;
}
},
actions: {
startCountdown({ commit }) {
return setInterval(() => commit('decrementCountdown'), 1000);
}
}
});
// Component.vue
<template>
<div>{{ countdown }}</div>
</template>
<script>
export default {
computed: {
countdown() {
return this.$store.state.countdown;
}
},
mounted() {
this.timer = this.$store.dispatch('startCountdown');
},
beforeDestroy() {
clearInterval(this.timer);
}
};
</script>
注意事项
- 清除定时器:务必在组件销毁时通过
beforeDestroy或beforeUnmount生命周期清除定时器或动画帧,避免内存泄漏。 - 性能优化:对于长时间倒计时,可改用服务器时间同步或 Web Worker 避免主线程阻塞。
- 格式化显示:通过计算属性动态格式化时间显示,支持
HH:MM:SS等自定义格式。 - 事件通知:通过
$emit在倒计时结束时触发父组件回调。







