vue实现防抖节流
防抖(Debounce)的实现
防抖的核心思想是在事件触发后延迟执行回调函数,若在延迟时间内再次触发事件,则重新计时。适用于输入框搜索联想等场景。
封装防抖函数
function debounce(fn, delay) {
let timer = null;
return function(...args) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
在Vue组件中使用

export default {
methods: {
handleInput: debounce(function(searchText) {
// 实际业务逻辑
console.log(searchText);
}, 500)
}
}
模板绑定
<input @input="handleInput($event.target.value)" />
节流(Throttle)的实现
节流的核心思想是在固定时间间隔内只执行一次回调函数。适用于滚动事件、窗口调整等高频触发场景。

封装节流函数
function throttle(fn, interval) {
let lastTime = 0;
return function(...args) {
const now = Date.now();
if (now - lastTime >= interval) {
fn.apply(this, args);
lastTime = now;
}
};
}
在Vue组件中使用
export default {
methods: {
handleScroll: throttle(function() {
// 滚动处理逻辑
console.log(window.scrollY);
}, 200)
},
mounted() {
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
}
}
使用lodash库的简化方案
对于生产环境,推荐使用成熟的工具库如lodash:
import { debounce, throttle } from 'lodash';
export default {
methods: {
search: debounce(function(query) {
// API调用
}, 300),
scrollHandler: throttle(function() {
// 滚动处理
}, 100)
}
}
注意事项
- 防抖适合连续事件结束后触发,节流适合均匀间隔触发
- 移除事件监听时需确保使用相同的函数引用
- 在Vue 3的setup语法中,需用ref保持函数引用:
const search = debounce((val) => { console.log(val); }, 500);
性能优化建议
- 合理设置延迟时间(防抖通常300-500ms,节流通常100-200ms)
- 对于复杂计算操作优先使用防抖
- 高频UI更新场景适合用节流保持流畅度






