当前位置:首页 > VUE

vue实现倒计时功能

2026-02-09 09:10:22VUE

使用 Vue 实现倒计时功能

方法一:基于 setInterval 的简单倒计时

在 Vue 组件的 data 中定义倒计时初始值,并通过 setInterval 每秒更新剩余时间。

vue实现倒计时功能

<template>
  <div>{{ formattedTime }}</div>
</template>

<script>
export default {
  data() {
    return {
      seconds: 60, // 倒计时总秒数
      timer: null
    };
  },
  computed: {
    formattedTime() {
      const mins = Math.floor(this.seconds / 60);
      const secs = this.seconds % 60;
      return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
    }
  },
  mounted() {
    this.timer = setInterval(() => {
      if (this.seconds > 0) {
        this.seconds--;
      } else {
        clearInterval(this.timer);
      }
    }, 1000);
  },
  beforeDestroy() {
    clearInterval(this.timer);
  }
};
</script>

方法二:封装可复用的倒计时组件

将倒计时逻辑封装为独立组件,支持通过 props 传入初始时间。

vue实现倒计时功能

<template>
  <div>{{ formattedTime }}</div>
</template>

<script>
export default {
  props: {
    initialSeconds: {
      type: Number,
      default: 60
    }
  },
  data() {
    return {
      seconds: this.initialSeconds,
      timer: null
    };
  },
  computed: {
    formattedTime() {
      const mins = Math.floor(this.seconds / 60);
      const secs = this.seconds % 60;
      return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
    }
  },
  mounted() {
    this.startTimer();
  },
  methods: {
    startTimer() {
      this.timer = setInterval(() => {
        if (this.seconds > 0) {
          this.seconds--;
        } else {
          clearInterval(this.timer);
          this.$emit('timeup');
        }
      }, 1000);
    }
  },
  beforeDestroy() {
    clearInterval(this.timer);
  }
};
</script>

方法三:使用 requestAnimationFrame 实现高精度倒计时

适用于需要更高精度的场景(如动画同步)。

<template>
  <div>{{ formattedTime }}</div>
</template>

<script>
export default {
  data() {
    return {
      endTime: Date.now() + 60000, // 1分钟后结束
      remainingTime: 60000,
      animationFrame: null
    };
  },
  computed: {
    formattedTime() {
      const secs = Math.ceil(this.remainingTime / 1000);
      const mins = Math.floor(secs / 60);
      const remainingSecs = secs % 60;
      return `${mins}:${remainingSecs < 10 ? '0' : ''}${remainingSecs}`;
    }
  },
  mounted() {
    this.updateTime();
  },
  methods: {
    updateTime() {
      this.remainingTime = this.endTime - Date.now();
      if (this.remainingTime > 0) {
        this.animationFrame = requestAnimationFrame(this.updateTime);
      } else {
        this.remainingTime = 0;
      }
    }
  },
  beforeDestroy() {
    cancelAnimationFrame(this.animationFrame);
  }
};
</script>

方法四:结合 Vuex 管理全局倒计时状态

适用于需要跨组件共享倒计时状态的场景。

// store.js
export default new Vuex.Store({
  state: {
    countdown: 60
  },
  mutations: {
    decrementCountdown(state) {
      if (state.countdown > 0) state.countdown--;
    }
  },
  actions: {
    startCountdown({ commit }) {
      return setInterval(() => commit('decrementCountdown'), 1000);
    }
  }
});

// Component.vue
<template>
  <div>{{ countdown }}</div>
</template>

<script>
export default {
  computed: {
    countdown() {
      return this.$store.state.countdown;
    }
  },
  mounted() {
    this.timer = this.$store.dispatch('startCountdown');
  },
  beforeDestroy() {
    clearInterval(this.timer);
  }
};
</script>

注意事项

  • 清除定时器:务必在组件销毁时通过 beforeDestroybeforeUnmount 生命周期清除定时器或动画帧,避免内存泄漏。
  • 性能优化:对于长时间倒计时,可改用服务器时间同步或 Web Worker 避免主线程阻塞。
  • 格式化显示:通过计算属性动态格式化时间显示,支持 HH:MM:SS 等自定义格式。
  • 事件通知:通过 $emit 在倒计时结束时触发父组件回调。

标签: 倒计时功能
分享给朋友:

相关文章

php实现留言板功能

php实现留言板功能

PHP 留言板功能实现 数据库设计 创建数据库表 messages,包含以下字段: id:自增主键 name:留言者姓名(VARCHAR) email:留言者邮箱(VARCHAR) content:…

js实现复制功能实现

js实现复制功能实现

使用document.execCommand方法(传统方式,已逐渐被弃用) 传统方式通过document.execCommand('copy')实现复制功能,需先选中文本。以下是一个完整示例: fu…

vue实现切换功能

vue实现切换功能

使用 v-show 实现切换功能 v-show 通过控制 CSS 的 display 属性来切换元素的显示状态,适合频繁切换的场景。性能较好,因为只是简单地切换显示/隐藏,不会重新渲染 DOM。 &…

vue 实现直播功能

vue 实现直播功能

实现直播功能的技术方案 在Vue中实现直播功能通常需要结合流媒体技术和前端播放器。以下是几种常见的技术方案: 使用WebRTC实现实时直播 WebRTC是一种支持浏览器实时通信的技术,适合低延迟的…

vue实现转发功能

vue实现转发功能

Vue实现转发功能的方法 使用Vue Router进行页面跳转转发 在Vue项目中,可以通过Vue Router的push或replace方法实现页面转发功能。需要在router/index.js中配…

vue实现删除功能

vue实现删除功能

Vue 实现删除功能的方法 在 Vue 中实现删除功能通常涉及以下几个步骤: 数据绑定与列表渲染 使用 v-for 指令渲染列表数据,并为每个列表项添加删除按钮。例如: <ul>…