说明:来自CSDN-问答板块,题主提问。
需求:如何通过表单控制倒计时开始时间,比如设定倒计时五分钟,循环几次,点击开始倒计时按钮,就让他从5分00秒,开始每秒减少,然后到0分00秒后,开始下一次循环,显示这是第几次循环,能不能点击开始倒计时,然后这个表单隐藏起来,还有就是计时结束之后,再设置计时得刷新才能正常。
一、解决代码
<template>
<div>
<div v-if="showForm">
循环的次数:<input type="number" v-model="cishu"><br>
每次几分钟:<input type="number" v-model="timeone"><br>
<button @click="startCountdown">开始倒计时</button>
</div>
<div>
<div v-if="counting">
第{{ currentCycle }}次循环 {{ formattedTime }}
</div>
<div v-else-if="finished">
倒计时完成
</div>
<div v-else-if="error">
输入错误
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
const countdownInterval = ref<NodeJS.Timeout | null>(null);
const cishu = ref<number>(5);
const timeone = ref<number>(3);
const currentCycle = ref<number>(1);
const counting = ref<boolean>(false);
const error = ref<boolean>(false);
const showForm = ref(true);
function startCountdown() {
if (isNaN(cishu.value) || isNaN(timeone.value)) {
error.value = true;
return;
}
error.value = false;
counting.value = true;
showForm.value = false;
let remainingSeconds = timeone.value * 60;
const countdownFn = () => {
if (remainingSeconds <= 0) {
if (currentCycle.value < cishu.value) {
currentCycle.value++;
remainingSeconds = timeone.value * 60;
} else {
counting.value = false;
finished.value = true;
return;
}
}
const minutes = Math.floor(remainingSeconds / 60);
const seconds = remainingSeconds % 60;
// 更新显示的时间
formattedTime.value = `${minutes} 分, ${seconds.toString().padStart(2, '0')} 秒`;
remainingSeconds--;
// 每秒递减
countdownInterval.value = setTimeout(countdownFn, 1000);
};
countdownFn();
// 清除倒计时
onMounted(() => {
clearTimeout(countdownInterval.value!);
});
}
// 格式化显示的时间
const formattedTime = ref<string>('00 分, 00 秒');
const finished = ref<boolean>(false);
watch([cishu, timeone], () => {
counting.value = false;
finished.value = false;
error.value = false;
});
watch(finished, (newValue) => {
if (newValue) {
window.location.reload();
}
});
</script>