Vue自定义指令中实现防抖和节流
防抖和节流
首先两者的区别
- 防抖:N秒内只触发一次,如果N秒内再次触发则重新计算时间;
- 节流:N秒内只触发一次,如果N秒内再次触发也不会执行;
防抖的实现
这里使用Vue自定义指令的形式实现,核心代码是事件绑定那段
/**
* @description Vue自定义指令
* @param argment[0] {type: String}
* @param argment[1] {type: Object} 在绑定组件中的各个生命周期中书写业务,这里使用inserted(){}
*/
Vue.directive('shake', {
/**
* @description () 在Dom父组件被挂载前的钩子函数中使用
* @param el {type: Object}绑定元素的节点
* @param binding {type: 所有合法的JS表达式}
* */
inserted(el, binding) {
let timerA = null;
el.addEventListener(
'click',
() => {
if (timerA) clearTimeout(timerA);
timerA = setTimeout(() => {
binding.value();
}, 400);
},
false
);
},
});
节流的实现
/**
*@description 节流 特定时间内一定会触发一次
* */
Vue.directive('throttling', {
inserted(el, binding) {
let timerB = null;
el.addEventListener('click', () => {
timerB = setTimeout(() => {
clearTimeout(timerB);
binding.value();
}, 2000);
});
},
});

浙公网安备 33010602011771号