…">
当前位置:首页 > VUE

用vue实现秒表应用

2026-01-20 01:11:18VUE

实现Vue秒表应用

创建Vue组件实现秒表功能,包含开始、暂停、重置按钮,并显示时间。

模板部分

<template>
  <div class="stopwatch">
    <div class="display">{{ formattedTime }}</div>
    <div class="controls">
      <button @click="start" :disabled="isRunning">开始</button>
      <button @click="pause" :disabled="!isRunning">暂停</button>
      <button @click="reset">重置</button>
    </div>
  </div>
</template>

脚本部分

<script>
export default {
  data() {
    return {
      isRunning: false,
      startTime: 0,
      elapsedTime: 0,
      timerInterval: null
    }
  },
  computed: {
    formattedTime() {
      const totalSeconds = Math.floor(this.elapsedTime / 1000)
      const minutes = Math.floor(totalSeconds / 60)
      const seconds = totalSeconds % 60
      const milliseconds = Math.floor((this.elapsedTime % 1000) / 10)

      return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${milliseconds.toString().padStart(2, '0')}`
    }
  },
  methods: {
    start() {
      if (!this.isRunning) {
        this.startTime = Date.now() - this.elapsedTime
        this.timerInterval = setInterval(this.updateTime, 10)
        this.isRunning = true
      }
    },
    pause() {
      if (this.isRunning) {
        clearInterval(this.timerInterval)
        this.isRunning = false
      }
    },
    reset() {
      clearInterval(this.timerInterval)
      this.isRunning = false
      this.elapsedTime = 0
    },
    updateTime() {
      this.elapsedTime = Date.now() - this.startTime
    }
  },
  beforeUnmount() {
    clearInterval(this.timerInterval)
  }
}
</script>

样式部分

用vue实现秒表应用

<style scoped>
.stopwatch {
  text-align: center;
  margin: 20px;
  font-family: Arial, sans-serif;
}

.display {
  font-size: 3em;
  margin-bottom: 20px;
}

.controls button {
  margin: 0 5px;
  padding: 8px 16px;
  font-size: 1em;
  cursor: pointer;
}

button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>

功能说明

  • 计时显示:格式为"分钟:秒.毫秒"(MM:SS.MS)
  • 开始按钮:启动计时器,开始计时
  • 暂停按钮:暂停当前计时,保留已计时间
  • 重置按钮:将计时归零,停止任何正在进行的计时
  • 状态控制:按钮在适当状态下禁用(如运行时禁用开始按钮)

扩展建议

  1. 添加计次功能,记录多个分段时间
  2. 实现本地存储,保存历史计时记录
  3. 增加声音提示功能
  4. 添加主题切换或自定义样式选项

标签: 秒表vue
分享给朋友:

相关文章

vue实现预览

vue实现预览

Vue实现文件预览的方法 使用Vue实现文件预览功能可以通过多种方式完成,具体取决于文件类型(图片、PDF、视频等)。以下是几种常见文件类型的实现方案。 图片预览 通过<input type=…

vue实现剪辑

vue实现剪辑

Vue 实现视频剪辑功能 在Vue中实现视频剪辑功能通常需要结合HTML5的<video>元素和第三方库(如FFmpeg.js或Video.js)。以下是几种常见的实现方法: 使用FFm…

vue实现模块

vue实现模块

Vue 实现模块化的方法 Vue 支持多种模块化开发方式,可以根据项目需求选择适合的方案。 使用单文件组件(SFC) 单文件组件是 Vue 最常用的模块化方式,将模板、脚本和样式封装在一个 .vue…

vue 实现跳转

vue 实现跳转

Vue 实现页面跳转的方法 在 Vue 中实现页面跳转通常可以通过以下几种方式实现,具体选择取决于项目需求和技术栈(如是否使用 Vue Router)。 使用 Vue Router 进行编程式导航…

vue实现vr

vue实现vr

Vue 实现 VR 的方法 Vue 可以与 WebVR 或 WebXR API 结合使用,通过 Three.js、A-Frame 等库实现 VR 效果。以下是几种常见方法: 使用 A-Frame 框…

vue 左右滑动实现

vue 左右滑动实现

Vue 实现左右滑动功能 使用 Vue 实现左右滑动功能可以通过多种方式完成,常见的有基于原生 JavaScript 事件监听、第三方库(如 Hammer.js)或 Vue 专用插件(如 vue-to…