当前位置:首页 > VUE

vue实现倒计时

2026-02-25 14:11:53VUE

Vue 实现倒计时的常见方法

使用 setInterval 实现基础倒计时

在 Vue 组件的 data 中定义倒计时相关变量:

data() {
  return {
    countdown: 60, // 初始倒计时秒数
    timer: null   // 存储定时器
  }
}

在方法中启动倒计时:

methods: {
  startCountdown() {
    this.timer = setInterval(() => {
      if (this.countdown > 0) {
        this.countdown--
      } else {
        clearInterval(this.timer)
      }
    }, 1000)
  }
}

在模板中显示倒计时:

<template>
  <button @click="startCountdown" :disabled="countdown !== 60">
    {{ countdown === 60 ? '获取验证码' : `${countdown}秒后重试` }}
  </button>
</template>

使用 computed 计算格式化时间

对于需要显示分钟和秒的倒计时:

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

使用 Vue 生命周期管理定时器

在组件销毁时清除定时器:

beforeDestroy() {
  clearInterval(this.timer)
}

使用第三方库实现更复杂倒计时

安装 vue-countdown 插件:

npm install vue-countdown

在组件中使用:

import VueCountdown from '@xkeshi/vue-countdown'

export default {
  components: {
    VueCountdown
  }
}

模板中使用:

<vue-countdown 
  :time="60 * 1000" 
  v-slot="{ minutes, seconds }">
  剩余时间:{{ minutes }}分{{ seconds }}秒
</vue-countdown>

使用 Date 对象实现精确倒计时

避免 setInterval 的误差:

methods: {
  preciseCountdown(endTime) {
    const now = new Date().getTime()
    const distance = endTime - now

    if (distance <= 0) {
      return clearInterval(this.timer)
    }

    this.countdown = Math.floor(distance / 1000)
  }
}

使用 CSS 动画增强视觉效果

为倒计时添加动画效果:

<transition name="fade">
  <span v-show="countdown > 0" class="countdown-text">
    {{ countdown }}
  </span>
</transition>

CSS 样式:

vue实现倒计时

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}
.countdown-text {
  font-size: 24px;
  color: #ff5722;
}

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

相关文章

vue实现全文检索

vue实现全文检索

Vue 实现全文检索的方法 客户端全文检索(适用于小型数据集) 使用 flexsearch 或 lunr.js 等轻量级库实现前端全文检索: import FlexSearch from 'flex…

vue实现微博发布动态

vue实现微博发布动态

使用Vue实现微博发布动态功能 创建Vue组件结构 新建一个WeiboPost.vue组件,包含文本框、图片上传和发布按钮: <template> <div class="we…

vue实现cs

vue实现cs

Vue 实现 CS(Client-Side)渲染的常见方法 Vue.js 是一个用于构建用户界面的渐进式框架,默认采用客户端渲染(CSR)。以下是几种常见的实现方式: 使用 Vue CLI 创建项目…

vue实现颜色闪烁

vue实现颜色闪烁

实现颜色闪烁的方法 在Vue中实现颜色闪烁效果可以通过CSS动画或JavaScript定时器动态修改样式。以下是两种常见的实现方式: 使用CSS动画实现 通过定义@keyframes动画规则,结合V…

vue实现登录权限

vue实现登录权限

Vue 实现登录权限方案 路由守卫控制访问权限 安装vue-router并配置路由守卫,在全局前置守卫中检查用户登录状态和权限。未登录用户访问受限路由时重定向到登录页。 // router.js r…

vue滚动插件实现

vue滚动插件实现

Vue 滚动插件实现方法 使用现有插件(推荐) 对于大多数场景,推荐使用成熟的 Vue 滚动插件,例如 vue-infinite-loading 或 vue-virtual-scroller。这些插件…