如何在vueJs方法中设置超时

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

我已经尝试过类似的东西,但它不起作用

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

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

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

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

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

这样你的Vue组件就可以在函数中访问了。

旁注:在这种特殊情况下,@ nospor接受的答案更清晰。 bind方法有点概括 – 例如,如果你想做一个匿名函数,它非常有用。

JavaScript中的上下文的经典问题。

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

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

我认为这也有效。

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

使用TimeOut调用递归:

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