vue3中的全局防抖节流指令

适用场景,一般业务当中存在查询、新增、编辑等操作类型,使用防抖有效防止疯狂点击增加多条数据问题

// 定义全局自定义指令
app.directive("antiShake", {
  // 在元素的 attribute 或事件监听器被应用之前调用   
  created(el, binding,) {
    let cbFun: NodeJS.Timeout|null = null;
    el.addEventListener("click", (event:any) => {
      event && event.stopImmediatePropagation();
      if (!cbFun) {
        cbFun = setTimeout(() => {
          binding.value()
        }, 2000);
      } else {
        clearTimeout(cbFun);
        cbFun = setTimeout(() => {
          binding.value()
        }, 2000);
      }
    }, true)
  },
});


//节流函数
app.directive("throttle", {
  created(el, binding,) {
    let throtTime = binding.value;
    if (!throtTime) {
      throtTime = 2000
    }
    let cbFun: NodeJS.Timeout|null = null;
    el.addEventListener("click", (event:any) => {
      if (!cbFun) {
        cbFun = setTimeout(() => {
          cbFun = null;
        }, throtTime);
      } else {
        event && event.stopImmediatePropagation();
      }
    }, true)
  },
});

页面使用方法

<template #footer>
          <span class="dialog-footer">
            <el-button type="warning" v-antiShake="add" @click="add()">确定</el-button>
          </span>
</template>