vue指令-防抖

 

// 1.设置v-throttle自定义指令
Vue.directive('throttle', {
  bind: (el, binding) => {
    let throttleTime = binding.value; // 防抖时间
    if (!throttleTime) { // 用户若不设置防抖时间,则默认2s
      throttleTime = 2000;
    }
    let cbFun;
    el.addEventListener('click', event => {
      if (!cbFun) { // 第一次执行
        cbFun = setTimeout(() => {
          cbFun = null;
        }, throttleTime);
      } else {
        event && event.stopImmediatePropagation();
      }
    }, true);
  },
});
// 2.为button标签设置v-throttle自定义指令
<button @click="sayHello" v-throttle>提交</button>

 

// 1.设置v-throttle自定义指令Vue.directive('throttle', {  bind: (el, binding) => {    let throttleTime = binding.value; // 防抖时间    if (!throttleTime) { // 用户若不设置防抖时间,则默认2s      throttleTime = 2000;    }    let cbFun;    el.addEventListener('click', event => {      if (!cbFun) { // 第一次执行        cbFun = setTimeout(() => {          cbFun = null;        }, throttleTime);      } else {        event && event.stopImmediatePropagation();      }    }, true);  },});// 2.为button标签设置v-throttle自定义指令<button @click="sayHello" v-throttle>提交</button>
posted @ 2025-01-14 16:27  磊~~  阅读(50)  评论(0)    收藏  举报