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

vue倒计时实现

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实现3d宇宙

vue实现3d宇宙

Vue实现3D宇宙效果 使用Three.js库 Three.js是一个强大的JavaScript 3D库,可以轻松集成到Vue项目中。安装Three.js依赖: npm install three…

vue实现bootstrap

vue实现bootstrap

Vue 中集成 Bootstrap 的方法 在 Vue 项目中集成 Bootstrap 可以通过以下方式实现,涵盖样式、组件和交互功能。 安装 Bootstrap 依赖 通过 npm 或 yarn…

vue 实现关闭

vue 实现关闭

Vue 实现关闭功能的方法 在Vue中实现关闭功能通常涉及组件销毁、模态框隐藏或路由跳转等场景。以下是几种常见实现方式: 销毁当前组件 使用v-if或v-show控制组件显示/隐藏,适用于局部组件:…

vue实现看板

vue实现看板

Vue 实现看板功能 使用 Vue 实现看板功能可以通过组件化开发、状态管理和拖拽库结合完成。以下是一个完整的实现方案: 基础项目结构 src/ ├── components/ │ ├── Ka…

vue实现ssr

vue实现ssr

Vue 实现 SSR(服务端渲染) Vue 的服务端渲染(SSR)允许在服务器端生成完整的 HTML 内容,再发送到客户端,提升首屏加载速度和 SEO 友好性。以下是实现 Vue SSR 的关键步骤和…

vue实现换页

vue实现换页

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