倒计时组件

<template>
  <span class="status-time" v-if="isShow" :style="'color: ' + textColor">
    <span v-if="isDayShow">{{ days }}天</span>{{ formatNum(hours) }}时{{ formatNum(minutes) }}分<span
      v-if="isSecondsShow"
      >{{ formatNum(seconds) }}秒</span
    ></span
  >
  <span v-else
    ><slot>0天0时0分<span v-if="isSecondsShow">0秒</span></slot></span
  >
</template>
<script>
import moment from "moment";

export default {
  props: {
    timestamp: {
      type: Number | String,
      required: true
    },
    textColor: {
      type: String,
      default: "#FF0000"
    },
    isSecondsShow: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      days: 0,
      hours: 0,
      minutes: 0,
      seconds: 0,
      timer: null,
      isShow: true,
      isDayShow: true
    };
  },
  created() {
    this.calculate();
    this.timer = setInterval(() => {
      this.calculate();
    }, 1000);
  },
  destroyed() {
    clearInterval(this.timer);
  },
  methods: {
    calculate() {
      // console.log(this.timestamp,'timestamptimestamptimestamp');
      // if (moment(this.timestamp).isValid()) return;
      const now = moment();
      const end = moment(this.timestamp);
      const duration = moment.duration(end.diff(now));
      this.days = Math.floor(duration.asDays());
      this.hours = duration.hours();
      this.minutes = duration.minutes();
      this.seconds = duration.seconds();
      // console.log(this.days + '天'+ this.hours + '时'+  this.minutes +'分');
      if (this.days > 0) {
        this.isDayShow = true;
      } else {
        this.isDayShow = false;
      }
      if (
        this.days <= 0 &&
        this.hours <= 0 &&
        this.minutes <= 0 &&
        this.seconds <= 0
      ) {
        clearInterval(this.timer); // 停止计时器
        this.isShow = false;
      }
    },
    formatNum(num) {
      return num < 10 ? "0" + num : "" + num;
    }
  }
};
</script>
<style lang="scss" scoped>
.status-time {
  // width: 80px;
  color: #ff0000;
  // font-size: 14px;
  // border: 1px solid #CB0200;
  border-radius: 3px;
  line-height: 17px;
  padding: 0 5px;
  text-align: center;
  display: inline-block;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
}
</style>

posted on 2026-04-21 14:26  jv_coder  阅读(4)  评论(0)    收藏  举报