Vue 中使用防抖函數
這篇文章也是銜接我之前文章,輸入內容延遲顯示。
一般防抖函數,一般都是自己寫,或者直接搜的類似這種
function debounce(fn,wait){
var timer = null;
return function(){
if(timer !== null){
clearTimeout(timer);
}
timer = setTimeout(fn,wait);
}
}
Vue官網Demo
https://cn.vuejs.org/v2/guide/computed.html#偵聽器
我看到Vue官網 偵聽器 使用了lodash
這個組件
created: function () {
// _.debounce 是一個通過 Lodash 限制操作頻率的函數。
// 在這個例子中,我們希望限制訪問 yesno.wtf/api 的頻率
// AJAX 請求直到用戶輸入完畢才會發出。想要了解更多關於
// _.debounce 函數 (及其近親 _.throttle) 的知識,
// 請參考:https://lodash.com/docs#debounce
this.debouncedGetAnswer = \_.debounce(this.getAnswer, 500)
}
我就在想既然,官網都不用自己手寫的,那我也用一下這個。
lodash.debounce
先看 https://lodash.com/docs#debounce 文檔
由於我只用了防抖,所以我只安裝防抖函數
npm i --save lodash.debounce
使用
import debounce from 'lodash.debounce'
textChange: debounce(function() {
//注意這里如果使用箭頭函數的話, this為 undefined https://github.com/vue-styleguidist/vue-docgen-api/issues/23
// do sth
}, 300)
總結
已經有輪子的話,就不要自己造輪子,當然練習的時候可以自己造。