vue 实现多个倒计
Vue 实现多个倒计时的方法
在 Vue 中实现多个倒计时可以通过以下方式完成:
使用 setInterval 和 clearInterval
通过 Vue 的 data 或 ref(Composition API)存储倒计时数据,并使用 setInterval 和 clearInterval 控制计时逻辑。

<template>
<div v-for="(timer, index) in timers" :key="index">
倒计时 {{ index + 1 }}: {{ timer.remainingTime }} 秒
</div>
</template>
<script>
export default {
data() {
return {
timers: [
{ remainingTime: 60, intervalId: null },
{ remainingTime: 120, intervalId: null },
],
};
},
mounted() {
this.timers.forEach((timer, index) => {
timer.intervalId = setInterval(() => {
if (timer.remainingTime > 0) {
timer.remainingTime--;
} else {
clearInterval(timer.intervalId);
}
}, 1000);
});
},
beforeDestroy() {
this.timers.forEach((timer) => {
if (timer.intervalId) clearInterval(timer.intervalId);
});
},
};
</script>
使用 Vue 3 Composition API
在 Vue 3 中,可以使用 ref 和 onMounted 实现多个倒计时。

<template>
<div v-for="(timer, index) in timers" :key="index">
倒计时 {{ index + 1 }}: {{ timer.remainingTime }} 秒
</div>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
const timers = ref([
{ remainingTime: 60, intervalId: null },
{ remainingTime: 120, intervalId: null },
]);
onMounted(() => {
timers.value.forEach((timer) => {
timer.intervalId = setInterval(() => {
if (timer.remainingTime > 0) {
timer.remainingTime--;
} else {
clearInterval(timer.intervalId);
}
}, 1000);
});
});
onBeforeUnmount(() => {
timers.value.forEach((timer) => {
if (timer.intervalId) clearInterval(timer.intervalId);
});
});
</script>
使用第三方库(如 vue-countdown)
如果需要更复杂的功能,可以使用第三方库 vue-countdown 实现多个倒计时。
<template>
<div v-for="(time, index) in countdownTimes" :key="index">
<countdown :time="time" v-slot="{ minutes, seconds }">
倒计时 {{ index + 1 }}: {{ minutes }}:{{ seconds }}
</countdown>
</div>
</template>
<script>
import Countdown from 'vue-countdown';
export default {
components: { Countdown },
data() {
return {
countdownTimes: [60000, 120000], // 毫秒为单位
};
},
};
</script>
动态添加倒计时
如果需要动态添加倒计时,可以通过方法控制倒计时的增减。
<template>
<div v-for="(timer, index) in timers" :key="index">
倒计时 {{ index + 1 }}: {{ timer.remainingTime }} 秒
<button @click="removeTimer(index)">移除</button>
</div>
<button @click="addTimer">添加倒计时</button>
</template>
<script>
export default {
data() {
return {
timers: [],
};
},
methods: {
addTimer() {
const newTimer = {
remainingTime: 30,
intervalId: null,
};
newTimer.intervalId = setInterval(() => {
if (newTimer.remainingTime > 0) {
newTimer.remainingTime--;
} else {
clearInterval(newTimer.intervalId);
}
}, 1000);
this.timers.push(newTimer);
},
removeTimer(index) {
clearInterval(this.timers[index].intervalId);
this.timers.splice(index, 1);
},
},
beforeDestroy() {
this.timers.forEach((timer) => {
if (timer.intervalId) clearInterval(timer.intervalId);
});
},
};
</script>
注意事项
- 使用
setInterval时,确保在组件销毁时清除定时器以避免内存泄漏。 - 如果需要更精确的倒计时,可以使用
requestAnimationFrame或performance.now()替代setInterval。 - 在 Vue 3 中,推荐使用
Composition API结合ref和onMounted管理倒计时逻辑。






