vue实现全局自定义防抖

在开发中涉及到一些按钮操作,手写一个简单的防抖自定义指令。

//防抖实现
// main.js中加入点击防抖方法
const throttle = {
  bind: (el, binding) => {
    let throttleTime = binding.value // 防抖时间
    if (!throttleTime) { // 用户若不设置防抖时间,则默认1s
      throttleTime = 1000
    }
    let timer
    let disable = false
    el.addEventListener('click', event => {
      if (timer) {
        clearTimeout(timer)
      }
      if (!disable) { // 第一次执行(一点击触发当前事件)
        disable = true
      } else {
        event && event.stopImmediatePropagation()
      }
      timer = setTimeout(() => {
        timer = null
        disable = false
      }, throttleTime)
    }, true)
  }
}


// 1. main.js中全局注册指令
Vue.directive('throttle', throttle);

使用:

 <i @click="onNextPage" v-throttle="500" class="el-icon-arrow-right"></i>

猜你喜欢

转载自blog.csdn.net/qq_63310300/article/details/132809423