用vue3写一个计时器组件
这是一个基于Vue3的计时器组件的代码示例:
<template>
<div>
<h3>计时器</h3>
<div>{{ displayTime }}</div>
<button @click="startTimer" :disabled="timerRunning">开始</button>
<button @click="stopTimer" :disabled="!timerRunning">停止</button>
</div>
</template>
<script>
import { ref, watch, onMounted, onUnmounted } from "vue";
export default {
name: "Timer",
setup() {
const seconds = ref(0);
const timerRunning = ref(false);
const startTimer = () => {
timerRunning.value = true;
};
const stopTimer = () => {
timerRunning.value = false;
seconds.value = 0;
};
const displayTime = ref("00:00:00");
const pad = (num) => {
return ("0" + num).slice(-2);
};
const updateTime = () => {
const hours = Math.floor(seconds.value / 3600);
const minutes = Math.floor((seconds.value % 3600) / 60);
const secs = Math.floor(seconds.value % 60);
displayTime.value = `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
};
watch(timerRunning, (newVal) => {
if (newVal) {
const intervalId = setInterval(() => {
seconds.value++;
updateTime();
}, 1000);
onUnmounted(() => {
clearInterval(intervalId);
});
}
});
onMounted(() => {
updateTime();
});
return {
seconds,
timerRunning,
startTimer,
stopTimer,
displayTime,
};
},
};
</script>
该组件有一个计时器,可以开始和停止计时,并显示已经过去的时间。组件使用 Vue3 的 Composition API 编写,利用 ref 创建响应式数据, watch 监听变量的变化, onMounted 和 onUnmounted 分别在组件挂载和卸载时执行函数。
计时器的实现使用了 setInterval 定时器,每秒自增一次秒数,然后更新时间显示。在组件卸载时,使用 clearInterval 清除定时器。
这个组件只是一个简单的示例,可以根据具体需求进行修改和扩展。
原文地址: https://www.cveoy.top/t/topic/0w6 著作权归作者所有。请勿转载和采集!