2017-04-16 94 views
0

我有,我不知道如何解决的一个问题。Vue2:瞬间JS倒计时

我有一个结束日期的成分,我想显示与剩余的秒的倒数计时器。

我用JS时刻对于这一点,但我不知道如何在Vue2实现这一点。

我应该使用一个计算方法?

 computed: { 
      timer: function() { 
       var now = moment(); 
       var then = moment().add(180, 'seconds'); 
       return moment().to(then); 
       (function timerLoop() { 
        this.timer = countdown(then).toString(); 
        requestAnimationFrame(timerLoop); 
       })(); 
      }, 

问题是我必须在vue2显示它之前返回值。但我也必须使用requestAnimationFrame每秒更新一次。

任何人都可以帮我吗?什么是使用这个最好的方法? setInterval或requestAnimationFrame?我认为后者,因为在1页上会有100多个定时器,所以性能是必要的。

所以很长的故事,简而言之: Momentjs and countdown timer

如何创建这样的一个Vue2函数/方法/混入?每秒更新哪一个?

由于

回答

0

代替具有时间循环为每个定时器的话,建议具有单个间隔更新模型上的值的每个第二和使用的Vue的反应性触发更新所计算的属性。

I've created a pen where you easily can play around with number active timers to see how it impacts performance.

data() { 
     return { 
      interval: null, 
      now: new Date(), 
      dates: [], // Your dates here 
     } 
    }, 
    computed() { 
     timers() { 
      return this.dates.map(then => moment(this.now).to(then)) 
     }, 
    }, 
    mounted() { 
     this.interval = setInterval(() => { 
      this.now = new Date() 
     }, 1000) 
    }