[英]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.