Javascript 如何在 vueJs 方法中设置超时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37465289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:21:29  来源:igfitidea点击:

how to set timeout in a vueJs method

javascriptphpjquerylaravel-5vue.js

提问by user3757488

how I can use settimeout() function in a vuejs method?

如何在 vuejs 方法中使用 settimeout() 函数?

I have already tried something like this, but it doesn't work

我已经尝试过这样的事情,但它不起作用

fetchHole: function () { 
    //get data
},

addHole: function () {
    //my query add new
    setTimeout(function () { this.fetchHole() }, 1000)
},

I get this Error message : Uncaught TypeError: this.fetchHole is not a function

我收到此错误消息: Uncaught TypeError: this.fetchHole is not a function

回答by ceejayoz

Add a bind()call to your function declaration:

添加bind()对函数声明的调用:

setTimeout(function () { this.fetchHole() }.bind(this), 1000)

so that your Vue component's thisis accessible within the function.

以便您的 Vue 组件this可以在函数内访问。

Side note: @nospor's accepted answer is cleaner in this particular situation. The bindapproach is a bit more generalized - very useful if you want to do an anonymous function, for example.

旁注:@nospor 接受的答案在这种特殊情况下更清晰。该bind方法更通用 - 例如,如果您想执行匿名函数,则非常有用。

回答by nospor

Try this: setTimeout(this.fetchHole, 1000)because thisin anonymous function is attached to that anonymous function not to your main function

试试这个:setTimeout(this.fetchHole, 1000)因为this匿名函数附加到匿名函数而不是你的主函数

回答by Deiviz

The classic issue with contextual thisin JavaScript.

thisJavaScript 中上下文的经典问题。

The following part of code shows an easy solution - if you are using ES6 with Vuejs (default config with vuecli y babel). Use an arrow function

以下代码部分显示了一个简单的解决方案 - 如果您将 ES6 与 Vuejs 一起使用(默认配置为 vuecli y babel)。使用箭头函数

setTimeout(()=>{
   this.yourMethod()
},1000);

An arrow function does not have its own this. The thisvalue of the enclosing lexical scope is used;

箭头函数没有自己的this. 使用this封闭词法范围的值;

Arrow functions - JavaScript | MDN

箭头函数- JavaScript | MDN

回答by Rubens Barbosa

I think this works too.

我认为这也有效。

var self = this;
setTimeout(function () { self.fetchHole() } , 1000)

回答by Darlan Dieterich

Call recursive with TimeOut:

使用 TimeOut 递归调用:

    save: function () {
      this.progressToProced = 0
      this.progress()          
    },
    progress: function () {
      if (this.progressToProced < 100) {
        this.progressToProced++
        setTimeout(function () { this.progress() }.bind(this), 100)
      }
    }

回答by Gamitha Anjana

You can try :

你可以试试 :

addHole:function(){
  let vm = this
  setTimeout(function(){vm.fetchHole()}, 1000)
}