vue自定义指令 - 防抖节流

141 阅读1分钟

防抖(Debounce)

防抖指令的作用是在用户触发事件(如点击)后,等待一段时间再执行绑定的函数。如果在等待期间再次触发事件,则重新开始计时。这样可以避免在短时间内频繁触发事件导致的性能问题。

节流(Throttle)

节流指令的作用是在用户触发事件后,每隔一段时间执行一次绑定的函数。这样可以避免在短时间内频繁触发事件导致的性能问题,同时保证函数在一定时间内至少执行一次。

新建文件directive.js,在mian.js全局注册并使用

export default {
  install(Vue) {
    //防抖指令
    Vue.directive('debounce', {
      bind(el, binding, vnode) {
        let debounceTime = binding.arg || 1000;
        let handler = binding.value.fn;
        let args = binding.value.args || [];
        let timer = null;
        el.addEventListener('click', () => {
          if (timer) {
            clearTimeout(timer);
          }
          timer = setTimeout(() => {
            handler(...args);
          }, debounceTime);
        });
      }
    });
    //节流
    Vue.directive('throttle', {
      bind(el, binding, vnode) {
        let throttleTime = binding.arg || 1000;
        let handler = binding.value.fn;
        let args = binding.value.args || [];
        let timer = null;
        el.addEventListener('click', () => {
          if (timer) {
            return;
          }
          timer = setTimeout(() => {
            handler(...args);
            timer = null;
          }, throttleTime);
        });
      }
    });
  }
}

然后,你可以在模板中使用这两个指令:

<!-- 使用防抖指令 -->
<button v-debounce="{ fn: handleClick }">防抖按钮</button>
<button v-debounce="{ fn: handleClick, args: ['参数1', '参数2'] }">防抖按钮</button>
<button v-debounce:500="{ fn: handleClick, args: ['参数1', '参数2'] }">防抖按钮(500ms)</button>

<!-- 使用节流指令 -->
<button v-throttle="{ fn: handleClick }">节流按钮</button>
<button v-throttle="{ fn: handleClick, args: ['参数1', '参数2'] }">节流按钮</button>
<button v-throttle:500="{ fn: handleClick, args: ['参数1', '参数2'] }">节流按钮(500ms)</button>



handleClick(arg1, arg2) { 
    console.log('按钮被点击了', arg1, arg2); 
}