簡體   English   中英

Lodash的_.debounce()在Vue.js中不起作用

[英]Lodash's _.debounce() not working in Vue.js

當修改Vue.js中名為q的組件屬性時,我正在嘗試運行一種名為query()的方法。

這失敗,因為this.query()未定義。 This是指我組件的實例,但是不包含方法。

這是相關的代碼部分,我試圖在其中查看組件屬性q並運行query()函數:

methods: {
  async query() {
    const url = `https://example.com`;
    const results = await axios({
      url,
      method: 'GET',
    });
    this.results = results.items;
  },
  debouncedQuery: _.debounce(() => { this.query(); }, 300),
},
watch: {
  q() {
    this.debouncedQuery();
  },
},

錯誤:

TypeError:_this2.query不是函數

如果我按如下方式編寫debounce()調用,則TypeError: expected a function在頁面加載時更早出現TypeError: expected a function錯誤。

debouncedQuery: _.debounce(this.query, 300),

問題來自您在_.debounce定義的arrow函數的詞法范圍。 this綁定到您要在其中定義的對象,而不是實例化的Vue實例。

如果將箭頭功能切換為常規功能,則范圍將正確綁定:

methods: {
  // ...
  debouncedQuery: _.debounce(function () { this.query(); }, 300)
}

我們可以用幾行代碼通過普通的JS(ES6)來實現:

function update() {

    if(typeof window.LIT !== 'undefined') {
        clearTimeout(window.LIT);
    }

    window.LIT = setTimeout(() => {
        // do something...
    }, 1000);

}

希望這會有所幫助:)

暫無
暫無

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

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