Vue倒计时组件

245 阅读1分钟
<template>
  <div :style="config.style">{{ lastTime }}</div>
</template>

<script>
const addZero = function(num) {
  return num < 10 ? "0" + num : String(num);
};
export default {
  props: {
    /**
     * @param time 分钟
     * @param style 传入样式
     */
    config: {
      type: Object,
      required: true,
      default: () => ({})
    }
  },
  data() {
    return {
      // 用户传进来的时间转化时间戳
      timeStamp: 0,
      // 记录刚开始时间
      curTimeStamp: "",
      // 记录结束时间
      endTimeStamp: "",
      // 剩余时间
      lastTime: "",
      // 剩余时间戳
      lastTimeStamp: "",
      interval: -1
    };
  },
  methods: {
    // 从外面调用
    pause() {
      clearInterval(this.interval);
    },
    reStart() {
      this.curTimeStamp = Date.now();
      this.endTimeStamp = this.curTimeStamp + this.lastTimeStamp;
      this.startCountDown();
    },

    countDownInit() {
      this.timeStamp = this.config.time * 60 * 1000;
      this.curTimeStamp = Date.now();
      this.endTimeStamp = this.curTimeStamp + this.timeStamp;
      this.lastTime = this.formatTimeStamp(this.timeStamp);
      this.startCountDown();
    },
    // 开始倒计时
    startCountDown() {
      this.interval = setInterval(_ => {
        this.lastTimeStamp = this.endTimeStamp - Date.now();
        // 时间结束
        if (this.lastTimeStamp > 0) {
          this.lastTime = this.formatTimeStamp(this.lastTimeStamp);
        } else {
          clearInterval(this.interval);
          this.lastTime = "00:00:00";
          this.$emit("timeEnd");
        }
      }, 1000);
    },
    formatTimeStamp(time) {
      let timeDate = new Date(time);
      // 暂时只支持到小时
      return `${addZero(timeDate.getUTCHours())}:${addZero(
        timeDate.getUTCMinutes()
      )}:${addZero(timeDate.getUTCSeconds())}`;
    },
    validateConfig() {
      if (!this.config.time) {
        this.time = "00:00:00";
        return false;
      }
      if (typeof this.config.time !== "number") {
        alert("config.time format should be a number");
        return false;
      }
      return true;
    }
  },
  created() {
    const valid = this.validateConfig();
    if (valid) {
      this.countDownInit();
    }
  }
};
</script>

<style>
</style>