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

自定义格式

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

注意事项

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

vue实现倒计时组件

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

相关文章

vue组件实现

vue组件实现

Vue 组件实现基础 Vue 组件是 Vue.js 的核心特性之一,允许将 UI 拆分为独立、可复用的模块。组件的实现包括定义、注册、数据传递和生命周期管理等。 定义组件 组件可以通过单文件组件(…

Vue组件实现方法

Vue组件实现方法

Vue组件的基本实现方法 Vue组件是Vue.js的核心概念之一,用于构建可复用的UI模块。以下是Vue组件的几种常见实现方式: 单文件组件(SFC) 使用.vue文件格式,将模板、脚本和样式封装…

vue实现组件循环

vue实现组件循环

Vue 实现组件循环的方法 在 Vue 中,可以通过 v-for 指令实现组件的循环渲染。以下是几种常见的实现方式: 使用 v-for 渲染数组 通过 v-for 遍历数组数据,动态生成组件列表:…

组件elementui

组件elementui

ElementUI 简介 ElementUI 是一套基于 Vue.js 的桌面端组件库,由饿了么前端团队开发并开源。它提供了丰富的 UI 组件(如按钮、表单、表格等),适合快速构建企业级中后台产品。…

Vue组件实现方法

Vue组件实现方法

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

vue动态组件实现

vue动态组件实现

动态组件的基本用法 在Vue中,动态组件通过<component>标签和is属性实现。is属性可以绑定组件名称或组件选项对象,实现动态切换。 <template> &l…