vue如何实现防抖
Vue 防抖的实现方法
在Vue中实现防抖(debounce)可以通过以下几种方式,根据不同的使用场景选择合适的方法。
使用 Lodash 的 debounce 函数
Lodash 是一个流行的 JavaScript 实用工具库,提供了 debounce 函数,可以直接在 Vue 中使用。
import { debounce } from 'lodash';
export default {
methods: {
handleInput: debounce(function(event) {
// 处理输入逻辑
console.log(event.target.value);
}, 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) {
this.debounce(() => {
console.log(event.target.value);
}, 500)();
},
},
};
在 Vue 3 中使用 Composition API
在 Vue 3 中,可以利用 ref 和 onMounted 等组合式 API 实现防抖。

import { ref, onMounted } from 'vue';
export default {
setup() {
const debounce = (func, delay) => {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func(...args);
}, delay);
};
};
const handleInput = debounce((event) => {
console.log(event.target.value);
}, 500);
return { handleInput };
},
};
在 Vue 模板中使用防抖
直接在模板中调用防抖函数,确保每次输入不会频繁触发事件。
<template>
<input @input="debounce(handleInput, 500)" />
</template>
使用 Vue 自定义指令
通过自定义指令,可以在全局或局部注册防抖功能。
Vue.directive('debounce', {
inserted(el, binding) {
let timeoutId;
el.addEventListener('input', () => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
binding.value();
}, 500);
});
},
});
在模板中使用:
<input v-debounce="handleInput" />
以上方法可以根据项目需求选择适合的方式实现防抖功能。






