vue 服务器端倒计时

2019-04-19  本文已影响0人  1462a2c022bc

<template>

  <span class="setInterval-box">{{time}}</span>

</template>

<script>

export default {

  name: 'Timer',

  data() {

    return {

      hour: 0,

      minute: 0,

      second: 0,

      timer: null

    }

  },

  props: {

    remainingTime: {

      type: String,

      default: '00:00:00'

    }

  },

  computed: {

    time() {

      return `${this.hour < 10 ? `0${this.hour}` : this.hour}:${parseInt(this.minute / 60, 0) < 10 ? `0${parseInt(this.minute / 60, 0)}` : parseInt(this.minute / 60, 0)}:${this.second < 10 ? `0${this.second}` : this.second}`

    }

  },

  mounted() {

    if (this.remainingTime) {

      const Array = this.remainingTime.split(':')

      this.hour = parseInt(Array[0], 0)

      this.minute = parseInt(Array[1], 0)

      this.second = parseInt(Array[2], 0)

      this.timeDown()

    }

  },

  methods: {

    timeDown() {

      let totalSecond = this.hour * 3600 + this.minute * 60 + this.second;

      const second2Time = (seconds) => {

        this.hour = parseInt(seconds / 3600, 0);

        this.minute = parseInt(seconds % 3600, 0);

        this.second = parseInt(seconds % 3600 % 60, 0);

      };

      this.timer = setInterval(() => {

        if (totalSecond) {

          totalSecond -= 1;

          second2Time(totalSecond)

        } else {

          clearInterval(this.timer)

        }

      }, 1000)

    }

  },

  beforeDestroy() {

    clearInterval(this.timer)

  },

}

</script>

上一篇 下一篇

猜你喜欢

热点阅读