以下是一个使用Vue 3编写的计时器组件示例:

<template>
  <div>
    <h2>计时器</h2>
    <div>{{ formatTime }}</div>
    <button @click="startTimer" v-if="!isRunning">开始</button>
    <button @click="stopTimer" v-else>停止</button>
    <button @click="resetTimer">重置</button>
  </div>
</template>

<script>
import { ref, watch, onBeforeUnmount } from 'vue';

export default {
  name: 'Timer',
  setup() {
    const time = ref(0); // 计时器的时间,单位为秒
    const isRunning = ref(false); // 是否正在计时

    const formatTime = computed(() => {
      const minutes = Math.floor(time.value / 60);
      const seconds = time.value % 60;

      return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
    });

    let intervalId = null;

    const startTimer = () => {
      if (!isRunning.value) {
        isRunning.value = true;
        intervalId = setInterval(() => {
          time.value++;
        }, 1000);
      }
    };

    const stopTimer = () => {
      if (isRunning.value) {
        isRunning.value = false;
        clearInterval(intervalId);
      }
    };

    const resetTimer = () => {
      time.value = 0;
      stopTimer();
    };

    onBeforeUnmount(() => {
      stopTimer();
    });

    return {
      time,
      isRunning,
      formatTime,
      startTimer,
      stopTimer,
      resetTimer
    };
  }
};
</script>

这个计时器组件使用了Vue 3的Composition API,包括refwatchonBeforeUnmount等函数。它包含了一个计时器的时间time、一个表示计时器是否正在运行的标志isRunning,以及formatTime计算属性用于格式化时间显示。

组件的setup函数中定义了计时器的开始、停止和重置方法,并在组件销毁前通过onBeforeUnmount钩子函数停止计时器。最后,将这些数据和方法暴露给模板进行渲染和交互

使用vue3写一个计时器

原文地址: https://www.cveoy.top/t/topic/hXSR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录