Vue lodash.debounce防抖函數


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)

總結

已經有輪子的話,就不要自己造輪子,當然練習的時候可以自己造。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM