vue倒数计时器无限循环

问题描述 投票:1回答:1

[嗨,我正在尝试使用一个倒数计时器,但尽管此方法有效,但每次运行时都会收到控制台错误,提示'组件渲染函数中可能存在无限的更新循环。'因此必须进行一些调整

export default {
  data: () => ({
    timeDiff: 0,
    time: {
      days: 0,
      hours: 0,
      minutes: 0,
      seconds: 0,
    },
  }),
  created(){
    this.countdown();
  },
  methods: {
    countdown() {
      setTimeout(() => {
        if (this.$store.state.allDataLoaded) {
          var countDownDate = new Date('December 17, 2019 03:24:00');
          var now = new Date();
          this.timeDiff = countDownDate - now;
          this.time.days = Math.floor(this.timeDiff / (1000 * 60 * 60 * 24));
          this.time.hours = Math.floor((this.timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
          this.time.minutes = Math.floor((this.timeDiff % (1000 * 60 * 60)) / (1000 * 60));
          this.time.seconds = Math.floor((this.timeDiff % (1000 * 60)) / 1000);
        } else {
          this.timeDiff = -1;
          this.time.days = 0;
          this.time.hours = 0;
          this.time.minutes = 0;
          this.time.seconds = 0;
        }
        this.countdown()
      }, 1000)
    },
  },
  computed: {
    timeDiffComp(){
      return this.timeDiff
    },
    timeComp(){
      return this.time
    },
  }
};
javascript vue.js countdown
1个回答
0
投票

var application = new Vue({
  template: '<div>{{ remaining.days }} days, {{ remaining.hours }} hours, {{ remaining.minutes }} mins, {{ remaining.seconds }} sec</div>',
  data:
    {
      counter: 0,
      countdown: new Date('2019-12-17T03:24:00Z')
    },
    created: function()
    {
      this.advance();
    },
    methods:
    {
      advance: function()
      {
        setTimeout(this.timer, 1000);
      },
      timer: function()
      {
        this.counter++;
        this.advance();
      }
    },
    computed:
    {
      remaining: function()
      {
        var tmp = this.counter + 1; // we just want to invalidate the cached computed value and thus trigger re-rendering of the template
        var timeDiff = this.countdown.getTime() - Date.now();
        return {
          days: Math.floor(timeDiff / (1000 * 60 * 60 * 24)),
          hours: Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
          minutes: Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60)),
          seconds: Math.floor((timeDiff % (1000 * 60)) / 1000),
        }
      }  
    },
    }).$mount('#app');
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>
© www.soinside.com 2019 - 2024. All rights reserved.