Vue 3 计时器组件示例:使用 Composition API 实现秒表功能
<p>"<template>\n <div>\n <h2>计时器</h2>\n <div>{{ formatTime }}</div>\n <button @click="startTimer" v-if="!isRunning">开始</button>\n <button @click="stopTimer" v-else>停止</button>\n <button @click="resetTimer">重置</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(() => {\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 = () => {\n if (!isRunning.value) {\n isRunning.value = true;\n intervalId = setInterval(() => {\n time.value++;\n }, 1000);\n }\n };\n\n const stopTimer = () => {\n if (isRunning.value) {\n isRunning.value = false;\n clearInterval(intervalId);\n }\n };\n\n const resetTimer = () => {\n time.value = 0;\n stopTimer();\n };\n\n onBeforeUnmount(() => {\n stopTimer();\n });\n\n return {\n time,\n isRunning,\n formatTime,\n startTimer,\n stopTimer,\n resetTimer\n };\n }\n};\n</script>\n"\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>
AI 优化版
原文地址:https://www.cveoy.top/t/topic/pGZS 著作权归作者所有。请勿转载和采集!