vue防抖怎么实现
防抖的基本概念
防抖(Debounce)是一种限制函数频繁调用的技术,确保函数在连续触发时只执行一次。适用于输入框搜索、窗口大小调整等场景。
在 Vue 中实现防抖的方法
使用 Lodash 的 _.debounce
Lodash 提供了现成的防抖函数,可直接在 Vue 中调用。
-
安装 Lodash:
npm install lodash -
在 Vue 组件中使用:
import { debounce } from 'lodash'; export default { methods: { handleInput: debounce(function() { console.log('防抖处理后的输入'); }, 500), } } -
在模板中绑定:
<input @input="handleInput" />
自定义防抖函数
如果不依赖 Lodash,可以手动实现防抖逻辑。
-
定义防抖函数:
function debounce(fn, delay) { let timer = null; return function() { if (timer) clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, arguments); }, delay); }; } -
在 Vue 组件中应用:
export default { methods: { handleInput: debounce(function() { console.log('自定义防抖处理'); }, 500), } }
使用 Vue 3 的 setup 语法
在 Vue 3 的 Composition API 中,可以通过 ref 和 onMounted 结合防抖逻辑。
-
定义防抖函数:
import { ref } from 'vue'; export default { setup() { const handleInput = debounce(() => { console.log('Composition API 防抖'); }, 500); return { handleInput }; } } -
模板绑定方式与选项式 API 相同。
注意事项
- 防抖时间(如
500ms)需根据实际场景调整,过长会影响响应速度,过短可能无法有效防抖。 - 如果需要在防抖函数中访问 Vue 实例的
this,需确保函数绑定正确(如使用箭头函数或.apply(this))。







