vue 中實現 節流


vue 中實現 節流函數

fnThrottle(method, delay, duration) {
      var that = this;
      var timer = this.timer;
      var begin = new Date().getTime();
      return function() {
        var current = new Date().getTime();
        clearTimeout(timer);
        if (current - begin >= duration) {
          method();
          begin = current;
        } else {
          that.timer = setTimeout(function() {
            method();
          }, delay);
        }
      };
    },

須在data中定義一個timer

如何使用:

我的需求是在輸入框中輸入時,帶出搜索的結果,實時展示出來

所以我在watch中監聽了輸入框綁定的值

watch: {
    searchVal(newValue) {
      this.searchVal = newValue;
      //在這里調用,並執行
      this.fnThrottle(this.search, 500, 2000)();
    }
  }
methods:{
  search(){
    //請求函數
  }  
}

這樣就實現的在vue中的函數節流。

歡迎大家的指正。


免責聲明!

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



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