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() {
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(() => {
this.start();
}, 1000)
}
},
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 (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 ? this.zero(Math.floor((time / 86400)) % 30) : "00";
//月份,以实际平均每月秒数计算
month = Math.floor((time / 2629744)) > 0 ? this.zero(Math.floor((time / 2629744)) % 12) : "00";
//年份,按按回归年365天5时48分46秒算
year = Math.floor((time / 31556926)) > 0 ? Math.floor((time / 31556926)) : "0";
return `${mini}:${sec}`
} else {
return '00:00'
}
}
}
}
</script>

<style type="text/scss" scoped lang="">

</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>

  

posted @ 2019-04-29 15:32  ·悟空·  阅读(616)  评论(0)    收藏  举报