【问题标题】:VueJS : How to update value inside watcher without affecting the watcherVueJS:如何在不影响观察者的情况下更新观察者内部的值
【发布时间】:2021-04-27 06:34:54
【问题描述】:

我使用 Vue 制作了一个在线测验应用程序,其中每个问题都有自己的持续时间。我正在使用 watcher 进行倒计时并将其显示在网页上。我面临的问题是每次我更新时间以匹配下一个问题的时间时,倒计时会更快结束。如何在不中断当前倒计时的情况下更新观察者中的时间限制?

watch: {
    timerEnabled(value) {
      if (value) {
        setTimeout(() => {
          this.timeLimit--;
        }, 1000);
      }
    },
    timeLimit: {
      handler(value) {
        if (value >= 0 && this.timerEnabled) {
          setTimeout(() => {
            this.timeLimit--;
          }, 1000);
        }
        else{
          // set the timer to the next question's time limit and move to the next question
        }
      }
    }
  }

【问题讨论】:

    标签: javascript vue.js nuxt.js


    【解决方案1】:

    我想你可以试试这样的:

    data() {
      return {
        timer: null,
        timerCounter: 0
      }
    },
    methods: {
      setTimer(state) { // true enabled, false disabled
        if(state) {
          this.timerCount = // seconds
          this.timer = setTimeout(() => {
            timerCounter--;
            if(timerCounter <= 0) {
              this.setTimer(false);
              // go to next question
              this.setTimer(true);
            }
          }, 1000);
        } else {
          clearTimeout(this.timer);
        }
      }
    }
    

    第一次启动定时器只需要调用setTimer(true),例如在mounted()函数或按钮的点击事件中。

    如果您不希望在问题更改后重新启动计时器,请删除 this.setTimer(true);

    【讨论】:

    • 谢谢你的回答,但是我在观察者之外的计时器有一些问题,这就是为什么我改用观察者
    猜你喜欢
    • 2016-02-11
    • 2017-03-13
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    相关资源
    最近更新 更多