vue 动态指令防抖节流

防抖

/***

  • 防抖 单位时间只触发最后一次

  • binding.value 指令传递的参数 [fn,params,event,time]

  • fn - 执行事件

  • params - 传递的参数

  • time - 间隔时间

  • event - 事件类型 例:"click"

  • 使用实例:刷新

  • 也可简写成:刷新
    */

vue 2 写法

Vue.directive('debounce', {
  inserted: function (el, binding) {
    let [fn, params,event = "click", time = 1000] = binding.value
    let timer
    el.addEventListener(event, () => {
      timer && clearTimeout(timer)
      timer = setTimeout(() => fn(params), time)
    })
  }
})

vue 3 写法

app.directive('debounce', {
  mounted: function (el, binding) {
    let [fn, params,event = "click", time = 1000] = binding.value
    let timer
    el.addEventListener(event, () => {
      timer && clearTimeout(timer)
      timer = setTimeout(() => fn(params), time)
    })
  }
})

节流

/***

  • 节流 每单位时间可触发一次
  • 第一次瞬间触发,最后一次不管是否达到间隔时间依然触发
  • binding.value 指令传递的参数 [fn,params,event,time]
  • fn - 执行事件
  • params - 传递的参数
  • time - 间隔时间
  • event - 事件类型 例:"click"
  • 使用实例:刷新
  • 传递参数则:刷新
    */

vue 2 写法

Vue.directive("throttle", {
  inserted: function (el, binding) {
    let [fn, param, event = "click", time = 1000] = binding.value
    let timer, timer_end;
    el.addEventListener(event, () => {
      if(timer) {
        clearTimeout(timer_end);
        return timer_end = setTimeout(() => fn(param), time);
      }
      fn();
      timer = setTimeout(() => timer = null, time)
    })
  },
})

vue 3 写法

Vue.directive("throttle", {
  mounted: function (el, binding) {
    let [fn, param, event = "click", time = 1000] = binding.value
    let timer, timer_end;
    el.addEventListener(event, () => {
      if(timer) {
        clearTimeout(timer_end);
        return timer_end = setTimeout(() => fn(param), time);
      }
      fn();
      timer = setTimeout(() => timer = null, time)
    })
  },
})
上一篇:《深入浅出WPF》学习总结之Binding


下一篇:自定义指令