vue实现防抖节流
防抖(Debounce)实现
防抖的核心在于延迟执行,直到事件停止触发后一段时间才执行。适用于输入框搜索、窗口调整等场景。
在Vue中可以通过自定义指令或方法实现:
方法1:使用Lodash库的_.debounce
import _ from 'lodash';
export default {
methods: {
handleInput: _.debounce(function() {
// 实际业务逻辑
console.log('Debounced input');
}, 500)
}
}
方法2:原生JavaScript实现

export default {
data() {
return {
timeout: null
}
},
methods: {
handleInput() {
clearTimeout(this.timeout);
this.timeout = setTimeout(() => {
// 实际业务逻辑
console.log('Debounced input');
}, 500);
}
}
}
节流(Throttle)实现
节流的核心在于固定时间间隔内只执行一次。适用于滚动事件、高频点击等场景。
方法1:使用Lodash库的_.throttle

import _ from 'lodash';
export default {
methods: {
handleScroll: _.throttle(function() {
// 实际业务逻辑
console.log('Throttled scroll');
}, 1000)
}
}
方法2:原生JavaScript实现
export default {
data() {
return {
lastExecTime: 0
}
},
methods: {
handleClick() {
const now = Date.now();
if (now - this.lastExecTime >= 1000) {
// 实际业务逻辑
console.log('Throttled click');
this.lastExecTime = now;
}
}
}
}
自定义指令实现
创建可复用的防抖/节流指令:
// debounce.js
export default {
inserted(el, binding) {
let timer;
el.addEventListener('input', () => {
clearTimeout(timer);
timer = setTimeout(() => {
binding.value();
}, binding.arg || 500);
});
}
}
// throttle.js
export default {
inserted(el, binding) {
let lastExec = 0;
el.addEventListener('click', () => {
const now = Date.now();
if (now - lastExec >= (binding.arg || 1000)) {
binding.value();
lastExec = now;
}
});
}
}
// main.js
import debounce from './debounce';
import throttle from './throttle';
Vue.directive('debounce', debounce);
Vue.directive('throttle', throttle);
使用方式:
<input v-debounce:300="search" />
<button v-throttle:1000="submit">提交</button>
注意事项
- 在组件销毁时应当清除定时器,避免内存泄漏
- 时间间隔需要根据实际场景调整
- 对于复杂场景建议使用成熟的工具库如Lodash
- 在Vue3中可以使用
setup语法结合ref实现相同功能






