vue 中实现 节流

时间:2019-10-18
本文章向大家介绍vue 中实现 节流,主要包括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中的函数节流。

欢迎大家的指正。

原文地址:https://www.cnblogs.com/chris-zy/p/11699370.html