防抖
防抖,就是指触发事件后 n 秒后才执行函数,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。
防抖的作用是为了减少函数的执行次数,避免在短时间内多次触发同一事件而导致重复执行某一操作或发送请求等问题。
当使用v-debounce:click绑定到一个元素上时,会在点击事件处理程序中增加防抖的逻辑,确保点击事件只有在停止连续触发500毫秒后才会被触发。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| data() { return { num:1 } }, methods: { handleClick() { console.log(this.num+" click!"); this.num++ }, },
directives: { debounce: { inserted(el, binding) { let timer; el.addEventListener(binding.arg, () => { clearTimeout(timer); timer = setTimeout(() => { binding.value(); }, 500); }); } } }
|
1 2 3
| <template> <button v-debounce:click="handleClick">点击</button> </template>
|
节流
节流,就是指连续触发事件但是在 n 秒中只执行一次函数。节流会稀释函数的执行频率。
throttledClick
1
| <button @click="throttledClick(handleClick,1000)">节流-{{num}}</button>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| data() { return { num: 0, throttled: false } }, methods: { handleClick() { console.log(this.num + " click!"); this.num++ }, throttledClick(fn,wait) { if (!this.throttled) { fn() this.throttled = true; setTimeout(() => { this.throttled = false; }, wait); } }
|