Build a Countdown Timer Component in Vue.js

Build a Countdown Timer Component in Vue.js

Countdown timers drive urgency and boost conversions, especially on product pages. Here’s how to build a reusable countdown timer in Vue.js.

CountdownTimer.vue
<template>
  <div class="text-3xl font-bold text-center">
    {{ days }}d {{ hours }}h {{ minutes }}m {{ seconds }}s
  </div>
</template>

<script>
export default {
  name: 'CountdownTimer',
  props: {
    targetDate: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      days: 0,
      hours: 0,
      minutes: 0,
      seconds: 0,
      timer: null
    };
  },
  mounted() {
    this.updateTimer();
    this.timer = setInterval(this.updateTimer, 1000);
  },
  methods: {
    updateTimer() {
      const now = new Date();
      const then = new Date(this.targetDate);
      const diff = (then - now) / 1000;

      if (diff <= 0) {
        clearInterval(this.timer);
        this.days = this.hours = this.minutes = this.seconds = 0;
        return;
      }

      this.days = Math.floor(diff / 86400);
      this.hours = Math.floor((diff % 86400) / 3600);
      this.minutes = Math.floor((diff % 3600) / 60);
      this.seconds = Math.floor(diff % 60);
    }
  },
  beforeUnmount() {
    clearInterval(this.timer);
  }
};
</script>

<style scoped>
div {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
</style>
Using the CountdownTimer Component

To use this timer inside your Vue component (e.g., a landing page), follow these steps:

1. Import the Component

import CountdownTimer from './components/CountdownTimer.vue';

2. Register It in Your Parent Component

export default {
  components: {
    CountdownTimer
  }
};

3. Use It in the Template

<template>
  <div class="flex flex-col items-center justify-center p-8">
    <h1 class="text-4xl font-bold mb-4">Limited Time Offer!</h1>
    <CountdownTimer targetDate="2025-12-31T23:59:59" />
    <button class="mt-6 bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700">
      Grab the Deal Now
    </button>
  </div>
</template>

Bibliography:

The Editor Avatar

Leave a Reply

Your email address will not be published. Required fields are marked *