vue 简单制作倒计时

当vue单个虚拟页面中包含很多定时器时,定时器结束时间戳还是由后台返还给我们的时候,我首先想到的是使用过滤器,自认为构建一个全局的定时器数据处理是一个比较简单的方法,于是就使用了下面的方法:

  1. 第一个当然是在mian.js中,创建处理倒计时显示的格式的全局过滤器了:

在这里插入图片描述

Vue.filter('time_sort', function (value, formatString) {  
  var now_time = Date.parse(new Date())/1000 ;   
  value -= now_time;
  if(value <= 0 ){
      return '活动已结束!'
  }else{
    var dd,hh,mm,ss = null;
    dd = Math.floor(value / 60 / 60  / 24 );
    hh = Math.floor((value / 60  / 60 ) % 24 );
    mm = Math.floor((value / 60   ) % 60) ;
    ss = Math.floor((value ) % 60) ;
    dd = dd < 10 ? '0'+dd : dd;
    hh = hh < 10 ? '0'+hh : hh;
    mm = mm < 10 ? '0'+mm : mm;
    ss = ss < 10 ? '0'+ss : ss;
   return dd + "天" + hh + "小时" + mm + "分" + ss + "秒" ; 
  }
})
  1. 格式过滤器 处理好,我们就好获取后台数据了 ; 这里我就略过,下面是后台给数据格式,end_time是10位的时间戳;
    在这里插入图片描述

  2. 获得数据就需要对数据进行处理,定时每一秒减去一秒
    在这里插入图片描述

 var that = this;
      setInterval(()=>{
        var now_time = Date.parse(new Date())/1000 ; //获取当前时间戳
        for(var  key = 0 ; key < that.huodong_data.length ; key++){     
          that.huodong_data[key].end_time -= 1 ;  //获取结束时间秒 
          that.huodong_data[key].end_time += 1

      }
      },1000)
  1. 上面的方法写了当然就要用了,按照情况调用;(我是在获取数据成功时就调用了)

在这里插入图片描述

   //跳转到活动页面
    activity() {
      var that = this;
      that.axios.post('/product/huodong_list',{}).then(function(res){
        that.huodong_data = res.data 
        that.time_data_lis()
           })
    },

大致就是这个样子了,很多细节的问题,感觉没必要写,就这样,等我忘记了,回来一看应该还是能看的懂得!

Logo

前往低代码交流专区

更多推荐