vue中如何使用节流(throttle)函数

JavaScript 中的函数大多数情况下都是由用户主动调用触发的,除非是函数本身的实现不合 理,否则我们一般不会遇到跟性能相关的问题。但在一些少数情况下,函数的触发不是由用户直 接控制的。在这些场景下,函数有可能被非常频繁地调用,而造成大的性能问题。如下列一些场景

  • window.onresize 事件。
  • mousemove 事件。
  • 上传进度。

那么在Vue中怎么实现和使用一个节流函数呢,k看下面代码

    <div id="app">
        <button @click="handleClick">测试</button>
    </div>
// 节流函数
function throttle (fn, interval) {
    
    
  var _self = fn, // 保存需要被延迟执行的函数引用
    timer, // 定时器
    firstTime = true; // 是否是第一次调用
  return function () {
    
    
    var args = arguments;
    _me = this;
    if (firstTime) {
    
     // 如果是第一次调用不需要延迟
      _self.apply(_me, args); // 执行fn函数并且修正此函数中this所运行的上下文指向
      return firstTime = false;
    }
    if (timer) {
    
     // 如果定时器还在,说明前一次延迟执行还没有完成
      return false;
    }
    timer = setTimeout(function () {
    
     // 延迟一段时间执行
      clearTimeout(timer);
      timer = null;
      _self.apply(_me, args); // 执行fn函数并且修正此函数中this所运行的上下文指向
    }, interval || 500);
  }
}
var app = new Vue({
    
    
  el: '#app',
  data: {
    
    
    message: 'Hello Vue!'
  },
  methods: {
    
    
    /*正确用法*/
    handleClick: throttle(function (event) {
    
    
      console.log('this:', this);
      console.log('触发', event);
    }, 1000),
    /*
    错误用法
    handleClick: function (event) {
      throttle(function () {
        console.log('this:', this);
        console.log('触发', event);
      })
    }
    */
  }
})

猜你喜欢

转载自blog.csdn.net/qq_35432904/article/details/126573644