Vue自定义指令中实现防抖和节流

防抖和节流

首先两者的区别

  • 防抖:N秒内只触发一次,如果N秒内再次触发则重新计算时间;
  • 节流:N秒内只触发一次,如果N秒内再次触发也不会执行;

防抖的实现

这里使用Vue自定义指令的形式实现,核心代码是事件绑定那段

   /**
   * @description Vue自定义指令
   * @param argment[0] {type: String}
   * @param argment[1] {type: Object} 在绑定组件中的各个生命周期中书写业务,这里使用inserted(){}
   */
  Vue.directive('shake', {
    /**
     * @description () 在Dom父组件被挂载前的钩子函数中使用
     * @param el {type: Object}绑定元素的节点
     * @param binding {type: 所有合法的JS表达式}
     * */
    inserted(el, binding) {
      let timerA = null;
      el.addEventListener(
        'click',
        () => {
          if (timerA) clearTimeout(timerA);
          timerA = setTimeout(() => {
            binding.value();
          }, 400);
        },
        false
      );
    },
  });

节流的实现

  /**
   *@description 节流 特定时间内一定会触发一次
   * */
  Vue.directive('throttling', {
    inserted(el, binding) {
      let timerB = null;
      el.addEventListener('click', () => {
        timerB = setTimeout(() => {
          clearTimeout(timerB);
          binding.value();
        }, 2000);
      });
    },
  });
posted @   lutwelve  阅读(637)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示