…">
当前位置:首页 > 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 3 实现的简单登录功能示例,包含表单验证和基础交互逻辑: 创建 Vue 组件 <template> <div class="login-containe…

vue实现看板

vue实现看板

Vue 实现看板功能 使用 Vue 实现看板功能可以通过组件化开发、状态管理和拖拽库结合完成。以下是一个完整的实现方案: 基础项目结构 src/ ├── components/ │ ├── Ka…

vue 组件实现

vue 组件实现

Vue 组件实现方法 单文件组件 (SFC) 使用 .vue 文件格式,包含模板、脚本和样式三部分: <template> <div class="example">{{…

vue 实现长按

vue 实现长按

实现长按功能的基本思路 在Vue中实现长按功能,通常需要监听元素的mousedown或touchstart事件,启动一个计时器。当用户按住元素超过设定的时间阈值时,触发长按回调函数。如果在时间阈值内触…

vue实现Pop

vue实现Pop

Vue 实现 Popover 组件的方法 使用 Vue 内置指令 v-show/v-if 和事件监听 通过 Vue 的指令和事件绑定实现基础的 Popover 功能。定义一个布尔值控制 Popover…

vue 轮询实现

vue 轮询实现

轮询的基本概念 轮询是一种通过定时向服务器发送请求来获取最新数据的技术。适用于需要实时更新但无法使用WebSocket的场景。 使用setInterval实现轮询 在Vue组件中,可以通过setIn…