当前位置:首页 > 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>

样式部分

<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 实现视频开场动画 在 Vue 中实现视频开场动画可以通过结合 HTML5 的 <video> 标签和 Vue 的过渡效果或生命周期钩子来完成。以下是具体实现方法: 安装依赖…

vue实现好评弹框

vue实现好评弹框

Vue 实现好评弹框的方法 使用 Vue 实现好评弹框可以通过组件化方式完成,结合动态数据绑定和事件处理。以下是具体实现步骤: 1. 创建弹框组件 新建一个 RatingDialog.vue…

vue实现简单的弹窗

vue实现简单的弹窗

使用 Vue 实现简单弹窗 组件基础结构 创建一个名为 Modal.vue 的组件文件,包含模板、脚本和样式部分: <template> <div class="modal-…

vue 实现简单登陆

vue 实现简单登陆

以下是一个使用 Vue 3 实现的简单登录功能示例,包含表单验证和基础交互逻辑: 创建 Vue 组件 <template> <div class="login-contain…

vue公共列表的实现

vue公共列表的实现

实现 Vue 公共列表组件 公共列表组件通常用于展示重复结构的数据,例如商品列表、用户列表等。以下是一个典型的实现方式: 基础实现 创建可复用的列表组件 List.vue: <templ…

vue手写签名如何实现

vue手写签名如何实现

实现手写签名的基本思路 在Vue中实现手写签名功能,通常需要借助HTML5的Canvas API来捕获用户的绘制操作。核心流程包括初始化画布、监听触摸/鼠标事件、记录轨迹以及生成签名图片。…