vue 定时器组件

<template>
  <span>
    <i v-text="msg"></i>
  </span>
</template>

<script>
  export default {
    name: "Timer",
    props: ['time'], // 接收 时间为秒
    data() {
      return {
        msg: '',
        timer: null,
        myTime: null,
      }
    },
    components: {},
    mounted() {
      this.myTime = this.time;
      this.start();
    },
    methods: {
      start() {
        let _this = this;

        function setTime() {
          if (_this.myTime == 0) {
            _this.msg = '00:00';
            _this.$emit('callback')
            clearTimeout(_this.timer)
            _this.timer = null;
          } else {
            _this.msg = _this.getText(_this.myTime);
            _this.myTime--;
            _this.timer = setTimeout(() => {
              setTime();
            }, 1000)
          }
        }
        setTime();
      },
      zero: function (n) { // 补0
        var n = parseInt(n, 10);
        if (n > 0) {
          if (n <= 9) {
            n = "0" + n;
          }
          return String(n);
        } else {
          return "00";
        }
      },
      getText(time) {
        let year, month, day, hour, mini, sec;
        if (this.time > 0) {
          sec = this.zero(time % 60);
          mini = Math.floor((time / 60)) > 0 ? this.zero(Math.floor((time / 60)) % 60) : "00";
          // hour = Math.floor((time / 3600)) > 0? this.zero(Math.floor((time / 3600)) % 24) : "00";
          day = Math.floor((time / 86400)) > 0 ? f.zero(Math.floor((time / 86400)) % 30) : "00";
          //月份,以实际平均每月秒数计算
          month = Math.floor((time / 2629744)) > 0 ? f.zero(Math.floor((time / 2629744)) % 12) : "00";
          //年份,按按回归年365天5时48分46秒算
          year = Math.floor((time / 31556926)) > 0 ? Math.floor((time / 31556926)) : "0";
          return `${year}-${month}-${day}-${mini}:${sec}`
        } else {
          return '00:00'
        }
      }
    }
  }
</script>

<style type="text/scss" scoped lang="">
  i {
    color: red;
  }
</style>

 

 

<template>
    <div>
      <div>
        <timer :time="time1" @callback="getMark1"></timer>
      </div>
      <div>
        <timer :time="time2" @callback="getMark2"></timer>
      </div>
    </div>
</template>

<script>
  import timer from '@/components/Timer'
    export default {
        name: "Sign",
        data() {
            return {
              time1:121,  // 单位  秒
              time2: 30,
            }
        },
        components: {timer},
        mounted() {
        },
        methods: {
          getMark1 () {
            console.log('1111')
          },
          getMark2() {
            console.log('2222')
          }
        }
    }
</script>

<style scoped lang="">

</style>

  

猜你喜欢

转载自www.cnblogs.com/tengrl/p/10790669.html