0
点赞
收藏
分享

微信扫一扫

vue 防抖和节流的实现(2)----指令

两者的区别,

  • 防抖:N秒内只触发一次,如果N秒内再次触发则重新计算时间;
  • 节流:N秒内只触发一次,如果N秒内再次触发也不会执行;


防抖实现

通过v-shake指令实现

    Vue.directive('shake', {
bind: (el , binding) => {
let shakeTime = el.getAttribute('time') || 2000; //防抖时间
let timerA = null;
el.addEventListener('click', () => {
if (timerA) {
clearTimeout(timerA);
timerA = null;
}
// 定时执行
timerA = setTimeout(() => {
binding.value();
}, shakeTime);
}, false)
}
});

<!-- 调用防抖指令 -->
<button v-shake="onSubmit" time="2000">提交</button>


节流实现

​通过v-throttling指令实现

    Vue.directive('throttling', {
bind: (el , binding) => {
let throttlingTime = el.getAttribute('time') || 2000; //防抖时间
let timerB = null;
el.addEventListener('click', () => {
timerB = setTimeout(() => {
clearTimeout(timerB);
binding.value();
}, throttlingTime);
});
}
});

<!-- 调用节流指令 -->
<button v-shake="onSubmit" time="5000">提交</button>




举报

相关推荐

0 条评论