vue防抖怎么实现
防抖的实现原理
防抖(Debounce)是一种限制函数频繁调用的技术,确保函数在最后一次调用后的指定时间间隔内只执行一次。适用于输入框搜索、窗口调整等场景。
Vue 中实现防抖的两种方式
方法一:使用 Lodash 的 _.debounce
Lodash 提供了现成的防抖函数,可直接在 Vue 组件中使用。
-
安装 Lodash

npm install lodash -
在组件中使用
import { debounce } from 'lodash'; export default { methods: { handleInput: debounce(function() { // 实际业务逻辑(如搜索请求) console.log('防抖处理后的输入'); }, 500), // 500ms 延迟 }, }; -
模板绑定

<template> <input @input="handleInput" /> </template>
方法二:手动实现防抖函数
若不依赖 Lodash,可通过闭包和定时器手动实现。
-
定义防抖工具函数
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() { console.log('手动防抖实现'); }, 500), }, };
注意事项
this绑定问题:手动实现时需通过apply确保上下文正确。- 清理定时器:组件销毁时(如路由跳转),需清除残留定时器以避免内存泄漏。
export default { beforeDestroy() { if (this.debouncedFn) { this.debouncedFn.cancel(); // Lodash 的取消方法 // 手动实现时需额外处理 } }, };
适用场景
- 搜索框输入联想
- 滚动事件监听
- 窗口大小调整事件
通过上述方法,可有效避免高频触发导致的性能问题。






