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