当前位置:首页 > VUE

vue记录时长前端实现

2026-03-27 01:27:42VUE

实现思路

前端记录时长通常涉及计时器、状态管理和持久化存储。Vue的响应式系统和生命周期钩子能很好地支持这类需求。

基础计时功能

使用setIntervaldata属性实现基础计时:

data() {
  return {
    seconds: 0,
    timer: null
  }
},
methods: {
  startTimer() {
    this.timer = setInterval(() => {
      this.seconds++
    }, 1000)
  },
  stopTimer() {
    clearInterval(this.timer)
  }
},
mounted() {
  this.startTimer()
},
beforeDestroy() {
  this.stopTimer()
}

持久化存储

结合localStorage实现关闭页面后仍保留计时:

data() {
  return {
    seconds: localStorage.getItem('timerSeconds') || 0
  }
},
watch: {
  seconds(newVal) {
    localStorage.setItem('timerSeconds', newVal)
  }
}

格式化显示

使用计算属性美化时间显示:

computed: {
  formattedTime() {
    const hours = Math.floor(this.seconds / 3600)
    const minutes = Math.floor((this.seconds % 3600) / 60)
    const secs = this.seconds % 60
    return `${hours}:${minutes}:${secs}`
  }
}

使用Vuex管理状态

对于复杂应用,建议使用Vuex集中管理计时状态:

// store.js
state: {
  timer: 0
},
mutations: {
  INCREMENT_TIMER(state) {
    state.timer++
  }
},
actions: {
  startTimer({ commit }) {
    setInterval(() => {
      commit('INCREMENT_TIMER')
    }, 1000)
  }
}

性能优化

对于精确计时,建议使用requestAnimationFrame

vue记录时长前端实现

methods: {
  startTimer() {
    let lastTime = performance.now()
    const update = () => {
      const now = performance.now()
      if (now - lastTime >= 1000) {
        this.seconds++
        lastTime = now
      }
      this.animationFrame = requestAnimationFrame(update)
    }
    this.animationFrame = requestAnimationFrame(update)
  },
  stopTimer() {
    cancelAnimationFrame(this.animationFrame)
  }
}

注意事项

  • 页面最小化时部分浏览器会降低定时器精度
  • 移动端浏览器可能为省电暂停后台页面计时
  • 长时间运行需考虑整数溢出问题
  • 多标签页同时运行时需使用BroadcastChannel同步状态

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

相关文章

vue实现滑块

vue实现滑块

Vue 实现滑块组件的方法 使用原生 HTML 和 Vue 指令 通过 Vue 的 v-model 和事件监听实现基础滑块功能。创建一个包含 input 元素的组件,类型设置为 range,并绑定到…

vue实现验证

vue实现验证

Vue 表单验证实现方法 在Vue中实现表单验证可以通过多种方式完成,以下是常见的几种方法: 使用Vuelidate库 Vuelidate是一个轻量级的Vue表单验证库,安装后可以通过简单的配置实现…

vue 分页 实现

vue 分页 实现

Vue 分页实现方法 使用第三方库(如 Element UI) Element UI 提供了现成的分页组件 el-pagination,适合快速集成。 安装 Element UI: npm ins…

vue前端实现

vue前端实现

Vue 前端实现基础步骤 安装 Vue.js 和相关依赖 通过 npm 或 yarn 安装 Vue.js,建议使用 Vue CLI 快速搭建项目。运行命令 npm install -g @vue/cl…

vue 实现hover

vue 实现hover

Vue 实现 Hover 效果的方法 在 Vue 中实现 hover 效果可以通过多种方式完成,以下是几种常见的方法: 使用 CSS 伪类 :hover 最简单的方式是直接使用 CSS 的 :hov…

vue计算属性 实现

vue计算属性 实现

Vue 计算属性的实现 计算属性(Computed Properties)是 Vue 中的一个核心功能,用于声明式地定义依赖其他属性的值。计算属性会缓存结果,只有当依赖的响应式数据发生变化时才会重新计…