setInterval不会在Vue中触发

时间:2019-04-21 07:42:24

标签: vue.js

im学习vue和setInterval不能像普通javascript一样工作?问题是我的更新功能没有被触发。 从一个按钮开始启动,然后将小时/分钟/秒绑定到带有v模型的输入字段,我在setInterval之前获取了所有console.logs。

export default Vue.extend({
  name: "timer-c",

  data() {
    return {
      startDate: undefined,
      hours: "",
      minutes: "",
      seconds: "",
      timeLeft: undefined,
      endDate: undefined,
      interval: undefined,
      text: "00:00:00",
      sub: undefined,
    };
  },

  methods: {
    start: function() {
      if (this.sub === undefined) {
        let sum = 0;
        if (this.seconds.match(/^\d+$/)) {
          sum = sum + this.seconds * 1000;
          console.log(sum);
        }
        if (this.minutes.match(/^\d+$/)) {
          sum = sum + this.minutes * 60 * 1000;
        }
        if (this.hours.match(/^\d+$/)) {
          sum = sum + this.hours * 60 * 60 * 1000;
        }
        if (sum === 0) {
          console.log(this.$refs.br_start);
          this.failed = true;
        } else {
          console.log(sum);
          this.failed = false;
          this.endDate = new Date(Date.now() + sum);
          console.log(this.endDate);
          this.startDate = new Date(Date.now());
          console.log(this.startDate);
          this.interval = setInterval(time => this.update, 1000);
          //this.sub = this.interval.subscribe(time => this.update(time));
        }
      }
    },
    update: function() {
      console.log('test');
      const timeRemaining = Math.round((Date.now() - this.endDate) / 1000);
      this.text = timeRemaining;
      if (new Date(Date.now()) >= this.endDate) {
        console.log("test");
      }
    },

1 个答案:

答案 0 :(得分:1)

尝试不返回函数而是执行

this.interval = setInterval(time => { this.update(time) }, 1000);