当前位置:首页 > VUE

vue实现倒计时组件

2026-01-12 06:20:15VUE

Vue 倒计时组件实现

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

基础实现方案

模板部分

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

脚本部分

<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 属性支持更灵活的显示格式:

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" />

自定义格式

vue实现倒计时组件

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

注意事项

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

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

相关文章

vue实现拖拽实现组件嵌套

vue实现拖拽实现组件嵌套

实现拖拽组件嵌套的核心思路 Vue中实现拖拽组件嵌套需要结合拖拽库(如vuedraggable)和组件递归渲染。核心在于动态管理嵌套数据结构,并通过事件传递实现层级更新。 安装必要依赖 推荐使用vu…

react组件如何通讯

react组件如何通讯

React 组件通讯方式 React 组件间的通讯方式主要包括以下几种方法,适用于不同场景下的数据传递和状态管理需求。 父子组件通讯(Props 传递) 父组件通过 props 向子组件传递数据或回…

Vue组件实现方法

Vue组件实现方法

Vue组件的基本实现 Vue组件是Vue.js的核心概念之一,允许将UI拆分为独立可复用的代码片段。组件的实现方式有多种,以下是常见的几种方法。 单文件组件(SFC) 单文件组件以.vue为后缀,将…

vue 实现toast组件

vue 实现toast组件

实现 Vue Toast 组件的方法 创建基础 Toast 组件 在 Vue 项目中创建一个基础 Toast 组件,通常包含消息内容和显示控制逻辑。 <template> &…

vue实现树形组件

vue实现树形组件

实现树形组件的基本思路 在Vue中实现树形组件通常涉及递归组件和动态数据渲染。核心是通过组件自身调用自身,逐层渲染嵌套的节点数据。 定义树形数据结构 树形数据通常是一个包含children属性的对象…

vue缩放组件实现

vue缩放组件实现

Vue 缩放组件实现方法 基于 CSS transform 实现缩放 通过 CSS 的 transform: scale() 属性实现基础缩放效果。在 Vue 中动态绑定 scale 值,结合鼠标事…