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中的函数节流。

欢迎大家的指正。

猜你喜欢

转载自www.cnblogs.com/chris-zy/p/11699370.html