How to use the throttle function in vue

Most of the functions in JavaScript are triggered by the user's active call. Unless the implementation of the function itself is unreasonable, we generally will not encounter performance-related problems. But in some rare cases, the triggering of the function is not directly controlled by the user. In these scenarios, the function may be called very frequently, causing big performance problems. The following scenarios

  • window.onresize incident.
  • mousemove event.
  • Upload progress.

So how to implement and use a throttling function in Vue, k see the following code

    <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);
      })
    }
    */
  }
})

Guess you like

Origin blog.csdn.net/qq_35432904/article/details/126573644