count-down.vue 1.89 KB
<template>
  <div class="count-down-wrapper" v-if="countDown !== ''">
    <i v-if="isShowIcon" class="time-icon"></i>
    <span>{{ countDown }}</span>
  </div>
</template>

<script>
export default {
  props: {
    leftTime: {
      type: Number,
      default: 0
    },
    isShowIcon: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      remainTime: this.$props.leftTime,
      countDown: "",
      timeoutId: null
    };
  },
  mounted() {
    this.countDown = this.formatTime().join(":");

    this.timeoutId = setInterval(() => {
      this.remainTime--;
      this.countDown = this.formatTime().join(":");
    }, 1000);
  },
  destroyed() {
    clearInterval(this.timeoutId);
  },
  watch: {
    countDown(val) {
      if (val === "") {
        clearInterval(this.timeoutId);
      }
    },
    leftTime(val) {
      if (!val) {
        this.countDown = "";
        clearInterval(this.timeoutId);
      }
    }
  },
  methods: {
    formatTime() {
      if (this.remainTime <= 0) {
        return [];
      }
      let remainTime = this.remainTime;

      const hourInSecond = 60 * 60;
      const numberOfHours = Math.floor(this.remainTime / hourInSecond);

      remainTime = remainTime - numberOfHours * hourInSecond;

      const numberOfMinutes = Math.floor(remainTime / 60);

      const numberOfSeconds = remainTime - numberOfMinutes * 60;

      return [numberOfHours, numberOfMinutes, numberOfSeconds].map(time => {
        return time < 10 ? `0${time}` : `${time}`;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.count-down-wrapper {
  display: flex;
  font-size: 32px;
  font-weight: bold;
  align-items: center;

  & > i {
    width: 30px;
    height: 30px;
    display: block;
    background: url("~statics/image/order/time-icon@3x.png");
    background-size: contain;
    background-position: center;
  }

  & > span {
    padding: 0 9px;
    @include num;
  }
}
</style>