用vue实现反远
实现防抖功能
防抖(Debounce)是一种优化高频触发事件的技术,确保在事件停止触发后一段时间才执行回调。Vue中可以通过自定义指令或方法实现。
在Vue组件中定义防抖方法:

methods: {
debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
},
handleInput() {
// 实际处理逻辑
}
}
使用自定义指令
创建全局防抖指令:
Vue.directive('debounce', {
inserted(el, binding) {
let timeout;
el.addEventListener('input', () => {
clearTimeout(timeout);
timeout = setTimeout(() => {
binding.value();
}, binding.arg || 500);
});
}
});
组件中使用指令:

<input v-debounce:300="search" />
使用lodash库
安装lodash后直接使用其防抖函数:
import { debounce } from 'lodash';
export default {
methods: {
search: debounce(function() {
// 执行搜索
}, 500)
}
}
在watch中使用防抖
对数据观察使用防抖处理:
watch: {
searchQuery: {
handler: debounce(function(newVal) {
this.fetchResults(newVal);
}, 500),
immediate: true
}
}
注意事项
防抖时间需要根据实际场景调整,输入框建议300-500ms,滚动事件可能需更短时间。在组件销毁时应当清除定时器,避免内存泄漏。对于需要立即执行的场景可考虑节流(Throttle)方案。






