vue倒计时

html

<div id="app">
  <h1 style="font-size:120px;margin:15%">剩余时间 {{ data }} </h1>
  <h2 style="font-size:42px;margin:5%">倒计时:<input type="text" style="width:50px;height:40px" v-model="total"><button @click='start'>开始</button>
  </h2>
</div>

 

js

data(){
  return{
    data:'00:00:00',
    leftTime: 0,
    total:0,
    flag:0
  }
},

methods:{
  start(){
    this.leftTime = this.total * 1000
    this.countTime()
    this.flag += 1
  },
  onload(){

    var that = this;

    // let d = Math.floor(that.leftTime / 1000 / 60 / 60 / 24); //天
    let h = Math.floor(that.leftTime / 1000 / 60 / 60 % 24); //小时
    let m = Math.floor(that.leftTime / 1000 / 60 % 60); //分钟
    let s = Math.floor(that.leftTime / 1000 % 60); //秒

    this.data = h+':'+m+':'+s;
  },
  countTime(){
    let that = this;
    that.leftTime = that.leftTime  - 1000;
    //控制台输出监控信息
    if (that.leftTime>0){
      console.log(that.leftTime);
      console.log('倒计时还剩'+that.leftTime/1000+'秒');
    }else if(that.leftTime<=0){
      console.log('倒计时已结束');
      return;
    }
    //定义变量 d,h,m,s保存倒计时的时间
    if (this.leftTime >= 0) {
      that.d = Math.floor(that.leftTime / 1000 / 60 / 60 / 24); //天
      that.h = Math.floor(that.leftTime / 1000 / 60 / 60 % 24); //小时
      that.m = Math.floor(that.leftTime / 1000 / 60 % 60); //分钟
      that.s = Math.floor(that.leftTime / 1000 % 60); //秒
    }

    //递归每秒调用countTime方法,显示动态时间效果
    that.data = that.h + ':' + that.m + ':' + that.s
    if(this.flag < 2){
      setTimeout(that.countTime, 1000);
    }
    else(
      alert("请刷新后重新开始!")
    )
  },

},

 

最终效果如下

 

posted @ 2020-08-15 14:02  远方的异特  阅读(163)  评论(0编辑  收藏  举报