热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何在vueJs方法中设置超时-howtosettimeoutinavueJsmethod

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

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

我收到此错误消息:未捕获TypeError:this.fetchHole不是一个函数

5 个解决方案

#1


21  

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)因为这个匿名函数附加到那个匿名函数而不是你的main函数

#2


29  

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组件就可以在函数中访问了。

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接受的答案更清晰。绑定方法有点概括 - 例如,如果你想做一个匿名函数,它非常有用。

#3


11  

The classic issue with contextual this in Javascript.

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);

#4


0  

I think this works too.

我认为这也有效。

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

#5


0  

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)
      }
    }

推荐阅读
author-avatar
心胸宽大的榛子lcf
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有