vue 實現指定日期之間的倒計時

效果圖如下

在這裏插入圖片描述
此處使用moment.js 日期處理類庫 使用方法如下

npm install moment 或者 yarn add moment

html

<div class="time-down">
  <div class="back">{{dayNum}}</div>
  <div class="font-14 date"></div>
  <div class="back">{{hourNum}}</div>
  <div class="font-14 date"></div>
  <div class="back">{{minuteNum}}</div>
  <div class="font-14 date"></div>
  <div class="back">{{secondNum}}</div>
  <div class="font-14 date"></div>
</div>

js

import moment from 'moment';
export default {
    name: 'TimeRangPage',
    props: {
      startTime: String,
      endTime: String
    },
    data () {
      return {
        days: 0,
        hours: 0,
        minutes: 0,
        seconds: 0,
        timeSetInterval: null,
        showTimeDown: false,
        showOver: false
      };
    },
    created () {
      if (moment(new Date()).isBefore(this.startTime)) {
        this.showTimeDown = true;
        this.timeDown();
      }
      if (moment(new Date()).isAfter(this.endTime)) this.showOver = true;
    },
    methods: {
      timeDown () {
        this.timeSetInterval = setInterval(() => {
          if (moment(this.startTime).isBefore(moment())) {
            this.showTimeDown = false;
            clearInterval(this.timeSetInterval);
            location.reload();
          }
          let dur = moment.duration(moment(this.startTime) - moment(), 'ms');
          this.days = dur.get('days');
          this.hours = dur.get('hours');
          this.minutes = dur.get('minutes');
          this.seconds = dur.get('seconds');
        }, 1000);
      }
    },
    computed: {
      dayNum () {
        if (this.days < 10) return '0' + this.days;
        return this.days;
      },
      hourNum () {
        if (this.hours < 10) return '0' + this.hours;
        return this.hours;
      },
      minuteNum () {
        if (this.minutes < 10) return '0' + this.minutes;
        return this.minutes;
      },
      secondNum () {
        if (this.seconds < 10) return '0' + this.seconds;
        return this.seconds;
      }
    }
  };
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章