首页 > 解决方案 > vuejs 中的 setTimeout 行为

问题描述

正如您在下面看到的,计时器应该msg在 90 年代之后更新,但它会立即更新。我知道,setIntervalwatch我需要知道为什么代码不起作用

我们所做的就是检查计数器是否高于 0,如果这样产生另一个超时并触发这个当前函数等等

var view = new Vue({
  el: '#app',
  data: {
    countDown: 90,
    msg: "There's still time.."
  },
  methods: {
    timer: function () {
      if (this.countDown > 0) {
        setTimeout(() => {
          this.countDown--
          this.timer()
        }, 1000);
      }
      else if(this.countDown === 0);
      {
        this.msg = 'You Ran Outta Time!'
      }
    }
  },
  
  created () {
    this.timer();
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Vue test</title>
</head>
<body>
  <div id="app">
    <h2>{{msg}}</h2>
  </div> 
</body>
</html>

标签: javascriptvue.js

解决方案


删除;后被else if(this.countDown === 0)视为语句,因此您的代码与以下内容相同:

  if (this.countDown > 0) {
            setTimeout(() => {
              this.countDown--
              console.log(this.countDown)
              this.timer()
            }, 1000);
          }
          else if(this.countDown === 0)
          {
                      
          }
   this.msg = 'You Ran Outta Time!'

var view = new Vue({
  el: '#app',
  data: {
    countDown: 90,
    msg: "There's still time.."
  },
  methods: {
    timer: function () {
      if (this.countDown > 0) {
        setTimeout(() => {
          this.countDown--
          console.log(this.countDown)
          this.timer()
        }, 1000);
      }
      else if(this.countDown === 0)
      {
      
        this.msg = 'You Ran Outta Time!'
      }
    }
  },
  
  created () {
    this.timer();
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Vue test</title>
</head>
<body>
  <div id="app">
    <h2>{{msg}}</h2>
  </div> 
</body>
</html>


推荐阅读