vue中实现的倒计时

386 阅读1分钟

倒计时的具体步骤

data(){
    return{
      activity:{},    //这是页面需要的数据
      flag:false, //关闭定时器的按钮
      h:'',   //时
      m:'',  //分
      s:''   //秒
    }
    
    //在mounted中发送请求 获取结束时间
    async mounted(){
        const result= await activityHome()
        if(result.code === 200){
            this.activity=result.data
           let time = setInterval(()=>{
              if(this.flag == true){   //当到点了之后清除定时器
                clearInterval(time)
              }
              this.timeDown(result.data.entTime)  //传到函数中
           },1000)
        } 
      },
//具体的步骤
     methods:{
          timeDown (data) {
            const endTime = new Date(data)   //请求的结束时间
            const startTime = new Date();   //当前的时间
            let leftTime = parseInt((endTime.getTime()-startTime.getTime())/1000)
            let h = this.formate(parseInt(leftTime/(60*60)%24)) 
            let m = this.formate(parseInt(leftTime/60%60))
            let s = this.formate(parseInt(leftTime%60))
            if(leftTime <= 0){   当小于等于0的时候打开开关 
              this.flag = true
            }
            this.h=h
            this.m=m
            this.s=s
          },
          formate (time) { 
          // 当是两位数的时候 就返回本身 如果不是就在前添加0
            if(time>=10){
              return time
            }else{
              return `0${time}`
            }
          }
        }