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
how to set timeout in a vueJs method
提问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 this
is accessible within the function.
以便您的 Vue 组件this
可以在函数内访问。
Side note: @nospor's accepted answer is cleaner in this particular situation. The bind
approach 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 this
in 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 this
in JavaScript.
this
JavaScript 中上下文的经典问题。
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
. Thethis
value of the enclosing lexical scope is used;
箭头函数没有自己的
this
. 使用this
封闭词法范围的值;
回答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)
}