vue3实现一个计时器功能 点击开始按钮开始计时 点击暂停按钮暂停计时 点击结束按钮清零 记录格式为00:00
时间: 2023-09-06 10:07:44 浏览: 118
好的,下面是一个简单的示例代码,实现了一个基本的计时器功能:
```
<template>
<div>
<div>{{ formatTime }}</div>
<button @click="start">开始</button>
<button @click="pause">暂停</button>
<button @click="stop">结束</button>
</div>
</template>
<script>
import { ref, computed } from 'vue';
export default {
setup() {
// 定义计时器相关的状态
const startTime = ref(0);
const pausedTime = ref(0);
const timer = ref(null);
// 格式化时间
const formatTime = computed(() => {
const totalSeconds = Math.floor((pausedTime.value - startTime.value) / 1000);
const minutes = Math.floor(totalSeconds / 60).toString().padStart(2, '0');
const seconds = (totalSeconds % 60).toString().padStart(2, '0');
return `${minutes}:${seconds}`;
});
// 开始计时
const start = () => {
startTime.value = Date.now() - pausedTime.value;
timer.value = setInterval(() => {
pausedTime.value = Date.now();
}, 1000);
};
// 暂停计时
const pause = () => {
clearInterval(timer.value);
};
// 停止计时
const stop = () => {
clearInterval(timer.value);
pausedTime.value = startTime.value = 0;
};
return {
formatTime,
start,
pause,
stop,
};
},
};
</script>
```
在这个示例中,我们使用了 Vue 3 的 Composition API 来管理计时器相关的状态。我们使用了 `ref` 来创建响应式的状态,并且使用了 `computed` 来计算格式化后的时间。
当用户点击开始按钮时,我们记录当前时间,并且使用 `setInterval` 来不断更新暂停时间,以实现计时器的效果。当用户点击暂停按钮时,我们清除计时器,当用户点击停止按钮时,我们清除计时器并且重置所有的状态。
注意,我们使用了 `padStart` 来确保时间的格式为 `00:00`,即如果某个值小于 10,我们会在前面添加一个 0。这样,我们就可以确保格式化后的时间始终是两位数的分钟和秒数。