vue的防抖实现
防抖的基本概念
防抖(Debounce)是一种优化高频触发事件的技术,确保事件在停止触发后延迟执行。适用于输入框搜索、窗口调整等场景。
Vue 中实现防抖的方法
方法一:使用 Lodash 的 _.debounce
安装 Lodash 并导入 debounce 方法:
npm install lodash
在 Vue 组件中使用:

import { debounce } from 'lodash';
export default {
methods: {
handleInput: debounce(function(event) {
// 实际逻辑,例如发起 API 请求
console.log(event.target.value);
}, 500) // 延迟 500 毫秒
}
}
模板中绑定事件:
<input @input="handleInput" />
方法二:手动实现防抖函数
自定义防抖函数,适用于不想引入 Lodash 的场景:

export default {
methods: {
debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
},
handleInput(event) {
const debouncedFn = this.debounce(() => {
console.log(event.target.value);
}, 500);
debouncedFn();
}
}
}
方法三:使用 Vue 3 的 setup 语法
在 Vue 3 的 Composition API 中实现:
import { ref } from 'vue';
import { debounce } from 'lodash';
export default {
setup() {
const searchQuery = ref('');
const debouncedSearch = debounce(() => {
console.log(searchQuery.value);
}, 500);
return {
searchQuery,
debouncedSearch
};
}
}
模板绑定:
<input v-model="searchQuery" @input="debouncedSearch" />
注意事项
- 内存泄漏:在组件销毁时清除防抖定时器,可通过
beforeUnmount生命周期处理。 - 参数传递:确保防抖函数能正确访问事件对象或组件上下文(如使用
apply或箭头函数)。 - 延迟时间:根据实际需求调整延迟时间(如搜索建议通常用 300-500ms)。
清除定时器的示例
export default {
data() {
return {
timeoutId: null
};
},
methods: {
debounce(func, delay) {
clearTimeout(this.timeoutId);
this.timeoutId = setTimeout(func, delay);
}
},
beforeUnmount() {
clearTimeout(this.timeoutId);
}
}






