簡體   English   中英

如何在 Vue.js 方法中使用 setTimeout?

[英]How to use setTimeout in a Vue.js method?

如何在 Vue.js 方法中使用setTimeout()函數?

我已經嘗試過這樣的事情,但它不起作用:

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

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

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

在你的函數聲明中添加一個bind()調用:

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

這樣您的 Vue 組件的this就可以在函數中訪問。

旁注:@nospor 接受的答案在這種特殊情況下更清晰。 bind方法更通用一些——例如,如果你想做一個匿名函數,這非常有用。

JavaScript 中上下文this的經典問題。

以下代碼部分顯示了一個簡單的解決方案 - 如果您將 ES6 與 Vuejs 一起使用(默認配置為 vuecli y babel)。 使用箭頭函數

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

箭頭函數沒有自己的this 使用封閉詞法范圍的this值;

箭頭函數 - JavaScript | MDN

試試這個: setTimeout(this.fetchHole, 1000)因為匿名函數中的this附加到那個匿名函數而不是你的主函數

我認為這也有效。

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

你可以試試 :

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM