防抖
/***
-
防抖 单位时间只触发最后一次
-
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)
})
},
})