<p>&quot;<template>\n  <div>\n    <h2>计时器</h2>\n    <div>{{ formatTime }}</div>\n    &lt;button @click=&quot;startTimer&quot; v-if=&quot;!isRunning&quot;&gt;开始</button>\n    &lt;button @click=&quot;stopTimer&quot; v-else&gt;停止</button>\n    &lt;button @click=&quot;resetTimer&quot;&gt;重置</button>\n  </div>\n</template>\n\n<script>\nimport { ref, watch, onBeforeUnmount } from 'vue';\n\nexport default {\n  name: 'Timer',\n  setup() {\n    const time = ref(0); // 计时器的时间,单位为秒\n    const isRunning = ref(false); // 是否正在计时\n\n    const formatTime = computed(() =&gt; {\n      const minutes = Math.floor(time.value / 60);\n      const seconds = time.value % 60;\n\n      return <code>${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}</code>;\n    });\n\n    let intervalId = null;\n\n    const startTimer = () =&gt; {\n      if (!isRunning.value) {\n        isRunning.value = true;\n        intervalId = setInterval(() =&gt; {\n          time.value++;\n        }, 1000);\n      }\n    };\n\n    const stopTimer = () =&gt; {\n      if (isRunning.value) {\n        isRunning.value = false;\n        clearInterval(intervalId);\n      }\n    };\n\n    const resetTimer = () =&gt; {\n      time.value = 0;\n      stopTimer();\n    };\n\n    onBeforeUnmount(() =&gt; {\n      stopTimer();\n    });\n\n    return {\n      time,\n      isRunning,\n      formatTime,\n      startTimer,\n      stopTimer,\n      resetTimer\n    };\n  }\n};\n</script>\n&quot;\n这个计时器组件使用了Vue 3的Composition API,包括<code>ref</code>、<code>watch</code>和<code>onBeforeUnmount</code>等函数。它包含了一个计时器的时间<code>time</code>、一个表示计时器是否正在运行的标志<code>isRunning</code>,以及<code>formatTime</code>计算属性用于格式化时间显示。\n\n组件的<code>setup</code>函数中定义了计时器的开始、停止和重置方法,并在组件销毁前通过<code>onBeforeUnmount</code>钩子函数停止计时器。最后,将这些数据和方法暴露给模板进行渲染和交互。</p>
Vue 3 计时器组件示例:使用 Composition API 实现秒表功能