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

安装:

npm install vue-countdown

使用示例:

<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循环数组的实现方法 在Vue中循环数组主要通过v-for指令实现,以下是几种常见用法: 基本数组循环 使用v-for指令遍历数组,可以通过(item, index)的语法获取当前项和索引值:…

vue实现添加用户

vue实现添加用户

Vue 实现添加用户功能 数据绑定与表单设计 在 Vue 中实现添加用户功能,首先需要设计一个表单,用于收集用户输入的数据。通过 v-model 实现双向数据绑定,确保表单数据与 Vue 实例中的数据…

vue实现关键词轮播

vue实现关键词轮播

Vue 实现关键词轮播 基础实现方案 使用 Vue 的 v-for 和 setInterval 实现基础轮播效果: <template> <div class="keyword…

vue实现绑卡的原理

vue实现绑卡的原理

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

vue实现轮询

vue实现轮询

实现轮询的基本方法 在Vue中实现轮询可以通过setInterval或setTimeout配合递归调用完成。轮询通常用于定期向服务器请求数据更新。 使用setInterval的简单示例: da…

vue 方法实现

vue 方法实现

在 Vue 中,方法的实现通常通过 methods 选项完成。以下是 Vue 方法实现的核心要点和示例: 基本方法定义 在 Vue 组件中定义方法时,需将函数声明放在 methods 对象内。这些…