当前位置:首页 > VUE

vue记录时长前端实现

2026-02-09 16:39:45VUE

Vue 前端实现时长记录功能

核心思路
通过 Vue 的响应式数据和生命周期钩子,结合浏览器 API 实现开始、暂停、继续和重置时长的功能。关键点在于利用 setInterval 计时并实时更新显示。

基础实现代码

<template>
  <div>
    <p>已记录时长: {{ formattedTime }}</p>
    <button @click="startTimer">开始</button>
    <button @click="pauseTimer">暂停</button>
    <button @click="resetTimer">重置</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      seconds: 0,
      timer: null,
      isRunning: false
    }
  },
  computed: {
    formattedTime() {
      const hours = Math.floor(this.seconds / 3600)
      const minutes = Math.floor((this.seconds % 3600) / 60)
      const secs = this.seconds % 60
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
    }
  },
  methods: {
    startTimer() {
      if (!this.isRunning) {
        this.isRunning = true
        this.timer = setInterval(() => {
          this.seconds++
        }, 1000)
      }
    },
    pauseTimer() {
      clearInterval(this.timer)
      this.isRunning = false
    },
    resetTimer() {
      clearInterval(this.timer)
      this.seconds = 0
      this.isRunning = false
    }
  },
  beforeUnmount() {
    clearInterval(this.timer)
  }
}
</script>

进阶功能实现

持久化存储
结合 localStorage 实现刷新页面不丢失记录:

mounted() {
  const savedTime = localStorage.getItem('recordedTime')
  if (savedTime) {
    this.seconds = parseInt(savedTime)
  }
},
watch: {
  seconds(newVal) {
    localStorage.setItem('recordedTime', newVal.toString())
  }
}

多段时长记录
记录多个时间段并统计总时长:

data() {
  return {
    timeSegments: [],
    currentStart: null
  }
},
methods: {
  startSegment() {
    this.currentStart = new Date()
  },
  endSegment() {
    if (this.currentStart) {
      const duration = Math.floor((new Date() - this.currentStart) / 1000)
      this.timeSegments.push(duration)
      this.currentStart = null
    }
  },
  totalDuration() {
    return this.timeSegments.reduce((sum, seg) => sum + seg, 0)
  }
}

性能优化方案

使用 requestAnimationFrame
替代 setInterval 实现更精确的计时:

methods: {
  startTimer() {
    if (!this.isRunning) {
      this.isRunning = true
      const startTime = Date.now() - this.seconds * 1000
      const update = () => {
        this.seconds = Math.floor((Date.now() - startTime) / 1000)
        if (this.isRunning) {
          requestAnimationFrame(update)
        }
      }
      requestAnimationFrame(update)
    }
  }
}

Worker 线程计时
避免主线程阻塞:

vue记录时长前端实现

// worker.js
let timer
self.onmessage = function(e) {
  if (e.data === 'start') {
    let seconds = 0
    timer = setInterval(() => {
      self.postMessage(++seconds)
    }, 1000)
  } else if (e.data === 'stop') {
    clearInterval(timer)
  }
}

// Vue组件
created() {
  this.worker = new Worker('./worker.js')
  this.worker.onmessage = (e) => {
    this.seconds = e.data
  }
}

注意事项

  • 页面隐藏时(切换标签页)建议暂停计时,可通过 document.visibilityState 监听
  • 移动端需注意锁屏情况,推荐使用 Background Timer 等插件
  • 长时间运行需考虑数字溢出问题,建议使用 BigInt 或分段记录

以上方案可根据实际需求组合使用,基础实现已能满足多数场景,进阶功能适合需要精确统计或离线保存的场景。

标签: 时长vue
分享给朋友:

相关文章

vue 实现单选

vue 实现单选

使用 v-model 绑定单选值 在 Vue 中,可以通过 v-model 绑定单选按钮的值。定义一个响应式数据(如 selectedOption),并将其与单选按钮的 value 属性关联。…

vue实现长按

vue实现长按

Vue 实现长按功能的方法 在 Vue 中实现长按功能可以通过原生事件监听或自定义指令完成。以下是几种常见实现方式: 使用原生事件监听 通过 @mousedown 和 @mouseup 或 @tou…

vue computed实现

vue computed实现

计算属性的基本用法 在Vue中,计算属性通过computed选项定义,用于声明依赖于其他属性的动态值。计算属性基于它们的依赖进行缓存,只有依赖发生变化时才会重新计算。 new Vue({ dat…

vue实现增加

vue实现增加

实现 Vue 中的新增功能 在 Vue 中实现新增功能通常涉及数据绑定、表单处理和状态管理。以下是几种常见的实现方式: 数据绑定与列表渲染 通过 v-model 绑定表单输入,使用数组的 push…

vue实现换页

vue实现换页

Vue实现页面切换的方法 在Vue中实现页面切换通常可以通过Vue Router来完成。Vue Router是Vue.js官方的路由管理器,用于构建单页面应用(SPA)。以下是几种常见的实现方式:…

vue 实现ztree

vue 实现ztree

在Vue中实现类似ZTree的功能,可以通过集成第三方库或自定义组件完成。以下是两种常见方法: 使用vue-tree组件 vue-tree是一个轻量级的Vue树形组件,支持复选框、懒加载等功能,适合…