当前位置:首页 > VUE

vue实现倒计时组件

2026-01-12 06:20:15VUE

Vue 倒计时组件实现

核心思路
通过 setIntervalsetTimeout 实现时间递减,结合 Vue 的响应式数据更新 UI。需注意组件销毁时清除定时器。

基础实现方案

模板部分

<template>
  <div class="countdown">
    {{ formattedTime }}
  </div>
</template>

脚本部分

vue实现倒计时组件

<script>
export default {
  props: {
    targetTime: { type: [Date, Number], required: true }, // 目标时间戳或Date对象
    format: { type: String, default: 'HH:mm:ss' } // 时间格式
  },
  data() {
    return {
      remainingTime: 0,
      timer: null
    };
  },
  computed: {
    formattedTime() {
      const hours = Math.floor(this.remainingTime / 3600);
      const minutes = Math.floor((this.remainingTime % 3600) / 60);
      const seconds = this.remainingTime % 60;
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    }
  },
  mounted() {
    this.startCountdown();
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  methods: {
    startCountdown() {
      const targetTimestamp = this.targetTime instanceof Date ? 
        Math.floor(this.targetTime.getTime() / 1000) : 
        Math.floor(this.targetTime / 1000);

      this.timer = setInterval(() => {
        const now = Math.floor(Date.now() / 1000);
        this.remainingTime = Math.max(0, targetTimestamp - now);

        if (this.remainingTime <= 0) {
          clearInterval(this.timer);
          this.$emit('finish');
        }
      }, 1000);
    }
  }
};
</script>

优化方向

自动销毁处理
添加 autoDestroy 属性控制倒计时结束后是否自动销毁组件:

props: {
  autoDestroy: { type: Boolean, default: false }
},
methods: {
  // 在定时器结束逻辑中追加
  if (this.remainingTime <= 0 && this.autoDestroy) {
    this.$destroy();
  }
}

动态格式支持
扩展 format 属性支持更灵活的显示格式:

vue实现倒计时组件

formattedTime() {
  const replacements = {
    'HH': Math.floor(this.remainingTime / 3600).toString().padStart(2, '0'),
    'mm': Math.floor((this.remainingTime % 3600) / 60).toString().padStart(2, '0'),
    'ss': (this.remainingTime % 60).toString().padStart(2, '0')
  };
  return this.format.replace(/HH|mm|ss/g, match => replacements[match]);
}

暂停/继续功能
添加控制方法:

methods: {
  pause() {
    clearInterval(this.timer);
    this.timer = null;
  },
  resume() {
    if (!this.timer) this.startCountdown();
  }
}

使用示例

基本调用

<Countdown :targetTime="new Date('2023-12-31 23:59:59')" @finish="handleFinish" />

自定义格式

<Countdown 
  :targetTime="1672502400000" 
  format="还剩HH小时mm分钟"
/>

注意事项

  1. 服务端渲染(SSR)环境下需使用 mounted 而非 created 启动定时器
  2. 时区问题建议统一使用 UTC 时间戳处理
  3. 高频更新场景可考虑使用 requestAnimationFrame 替代 setInterval

标签: 倒计时组件
分享给朋友:

相关文章

vue实现组件拖放

vue实现组件拖放

Vue 实现组件拖放的方法 使用 HTML5 原生拖放 API HTML5 提供了原生的拖放 API,可以通过 draggable 属性、dragstart、dragend、dragover 和 dr…

vue实现组件封装

vue实现组件封装

Vue 组件封装方法 封装组件的基本步骤 创建独立的 .vue 文件,包含 template、script 和 style 三个部分。通过 props 接收父组件传递的数据,使用 $emit 触发自…

vue动态组件实现

vue动态组件实现

Vue 动态组件实现方法 使用 component 标签与 is 属性 通过 Vue 内置的 <component> 标签和 is 属性实现动态组件切换。is 的值可以是已注册的组件名或导…

vue 实现组件刷新

vue 实现组件刷新

实现组件刷新的方法 在Vue中,组件刷新通常指重新渲染组件或重置组件状态。以下是几种常见的实现方式: 使用v-if控制渲染 通过v-if指令可以销毁并重新创建组件: <template>…

vue实现水印组件

vue实现水印组件

Vue 水印组件实现 基础水印组件实现 创建一个基础水印组件,通过 props 接收文本、颜色、大小等参数: <template> <div class="watermark…

vue组件的实现

vue组件的实现

Vue 组件的实现方式 Vue 组件可以通过多种方式实现,主要包括单文件组件(SFC)、全局注册和局部注册。以下是常见的实现方法: 单文件组件(SFC) 单文件组件是 Vue 最推荐的组件化开发方…