利用momentJs做一個倒計時組件(實例代碼)

今天抽空給大傢介紹下vue和moment做的一個倒計時,具體內容如下所示:

展示樣式:

<template>
    <div class="table-right flex-a-center">
        <div class="time-text">
            <span class="timeTextSpan" v-for="item,index of h" >{{item}}</span>
            <span class="timeTextSpan1" >: </span>
            <span class="timeTextSpan" v-for="item,index of m" >{{item}}</span>
            <span class="timeTextSpan1" >: </span>
            <span class="timeTextSpan" v-for="item,index of s" >{{item}}</span>
        </div>
    </div>
</template>
<script>
import moment from 'moment'
export default {
  props: {
    endTime: { }, //接收得最後時間 2021-12-17 16:29:20
  },
  data() {
    //這裡存放數據
    return {
      h:'00',
      m:'00',
      s:'00',
      timer:null
    };
  },
  watch: {
    endTime: {
      handler(e) {
        if (e) {
          let self = this
          clearInterval(this.timer)
          this.timer = setInterval(function(){self.init()},1000)
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    let self = this
    self.init()
    clearInterval(this.timer)
    this.timer = setInterval(function(){self.init()},1000)
  },
  //方法集合
  methods: {
    init(){
        let time =moment(this.endTime).diff(moment())
        if(time <= 0){
          clearInterval(this.timer)
          this.onOver()
          return
        }
        let t = time / 1000;
        let d = Math.floor(t / (24 * 3600));  //剩餘天數,如果需要可以自行補上
        let h = Math.floor((t - 24 * 3600 * d) / 3600) + d*24;  //不需要天數,把天數轉換成小時
        let _h = Math.floor((t - 24 * 3600 * d) / 3600)  //保留天數後得小時
        let m = Math.floor((t - 24 * 3600 * d - _h * 3600) / 60);
        let s = Math.floor((t - 24 * 3600 * d - _h * 3600 - m * 60));
       
        this.h = String(h).length == 1? '0'+String(h):String(h)
        this.m = String(m).length == 1? '0'+String(m):String(m)
        this.s = String(s).length == 1? '0'+String(s):String(s)
    },
    onOver() {
      this.$emit('over') //倒計時結束得回調
    }
 
  },
  beforeDestroy(){
    this.timer = null
    clearInterval(this.timer)
  }
}
</script>
<style lang='less' scoped>
@import url("@/assets/css/supplier.less");
 

  .table-right {
    font-size: 12px;
    color: #757e8a;
    .timeTextSpan{
      display: inline-block;
      width: 14px;
      height: 22px;
      text-align: center;
      background: #F1F0F0;
      border-radius: 2px;
      margin-right: 2px;
      font-size: 16px;
      color: #ff8a2b;
      font-weight: bold;
    }
    .timeTextSpan1{
      display: inline-block;
      width: 14px;
      text-align: center;
      vertical-align: bottom;
      color:#202D40;
      font-size: 16px;
      font-weight: bold;
    }
   
    .time-text {
      margin-left: 10px;
    }
  }
</style>

到此這篇關於利用momentJs做一個倒計時組件的文章就介紹到這瞭,更多相關momentJs倒計時組件內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: