vue自定义指令

2022-10-23  本文已影响0人  海豚先生的博客

防抖

Vue.directive('throttle', {
  bind: (el, binding) => {
    // 防抖时间
    let throttleTime = binding.value; 
    if (!throttleTime) {
      throttleTime = 2000;
    }
    let cbFun;
    el.addEventListener('click', event => {
      if (!cbFun) {
        cbFun = setTimeout(() => {
          cbFun = null;
        }, throttleTime);
      } else {
        event && event.stopImmediatePropagation();
      }
    }, true);
  },
});
// 为button标签设置v-throttle自定义指令
<button @click="sayHello" v-throttle>提交</button>
上一篇下一篇

猜你喜欢

热点阅读