当前位置:首页 > VUE

vue倒计时实现

2026-02-23 09:31:29VUE

Vue 倒计时实现方法

使用 setInterval 实现基础倒计时

在 Vue 组件中,可以通过 data 定义倒计时初始值,使用 setInterval 实现倒计时功能。

<template>
  <div>{{ countdown }}</div>
</template>

<script>
export default {
  data() {
    return {
      countdown: 60,
      timer: null
    }
  },
  mounted() {
    this.startCountdown()
  },
  methods: {
    startCountdown() {
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--
        } else {
          clearInterval(this.timer)
        }
      }, 1000)
    }
  },
  beforeDestroy() {
    clearInterval(this.timer)
  }
}
</script>

使用 computed 格式化显示时间

通过计算属性可以格式化倒计时显示,例如将秒数转换为分钟和秒。

computed: {
  formattedTime() {
    const minutes = Math.floor(this.countdown / 60)
    const seconds = this.countdown % 60
    return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`
  }
}

使用 Vue 插件 vue-countdown

对于更复杂的倒计时需求,可以使用第三方库 vue-countdown

vue倒计时实现

安装:

npm install vue-countdown

使用示例:

vue倒计时实现

<template>
  <countdown :time="time" :interval="1000">
    <template slot-scope="props">{{ props.minutes }}:{{ props.seconds }}</template>
  </countdown>
</template>

<script>
import Countdown from 'vue-countdown'

export default {
  components: { Countdown },
  data() {
    return {
      time: 60 * 1000 // 60秒
    }
  }
}
</script>

带回调函数的倒计时实现

倒计时结束后可以触发回调函数执行特定操作。

methods: {
  startCountdown() {
    this.timer = setInterval(() => {
      if (this.countdown > 0) {
        this.countdown--
      } else {
        clearInterval(this.timer)
        this.onCountdownEnd()
      }
    }, 1000)
  },
  onCountdownEnd() {
    console.log('倒计时结束')
    // 执行结束后的操作
  }
}

使用 requestAnimationFrame 实现更精确倒计时

对于需要高精度计时的情况,可以使用 requestAnimationFrame

methods: {
  startHighPrecisionCountdown() {
    const startTime = Date.now()
    const duration = 60000 // 60秒

    const updateCountdown = () => {
      const elapsed = Date.now() - startTime
      this.countdown = Math.max(0, Math.ceil((duration - elapsed) / 1000))

      if (elapsed < duration) {
        requestAnimationFrame(updateCountdown)
      }
    }

    requestAnimationFrame(updateCountdown)
  }
}

标签: 倒计时vue
分享给朋友:

相关文章

vue实现视频会议

vue实现视频会议

使用 Vue 实现视频会议 技术选型 Vue.js 作为前端框架,结合 WebRTC 技术实现实时音视频通信。常用的库包括: peerjs:简化 WebRTC 的点对点连接。 socket.io:用…

vue使用vr实现标注

vue使用vr实现标注

Vue 中使用 VR 实现标注的方法 在 Vue 项目中结合 VR 技术实现标注功能,可以通过 WebXR 和 Three.js 等库实现。以下为具体实现方法: 安装依赖 确保项目中已安装 Thre…

vue实现画圆弧并着色

vue实现画圆弧并着色

在 Vue 中实现画圆弧并着色 使用 Canvas API 绘制圆弧 在 Vue 组件的 mounted 钩子中,通过 Canvas API 绘制圆弧。创建一个 canvas 元素并获取其上下文:…

vue实现发送值接受值

vue实现发送值接受值

Vue 实现父子组件传值 父组件向子组件传值(props) 父组件通过 v-bind 或简写 : 向子组件传递数据。子组件通过 props 接收数据。 父组件代码: <template&g…

vue实现下拉刷新组件

vue实现下拉刷新组件

实现下拉刷新组件的核心思路 下拉刷新功能通常通过监听触摸事件、滚动位置和动画效果实现。Vue中可以利用自定义指令或封装组件完成,以下为两种常见实现方式。 基于自定义指令的实现 创建指令监听触摸事件,…

vue实现绑卡的原理

vue实现绑卡的原理

Vue 实现绑卡的原理 Vue 实现绑卡功能通常涉及前端表单处理、数据绑定、验证以及和后端 API 的交互。以下是实现绑卡功能的核心原理和步骤: 数据绑定与表单处理 Vue 通过 v-model 指…