vue实现防抖
Vue 实现防抖的方法
防抖(Debounce)是一种限制函数频繁调用的技术,确保函数在连续触发时只执行一次。以下是几种在 Vue 中实现防抖的方法。
使用 Lodash 的 _.debounce
Lodash 提供了现成的防抖函数,可以直接在 Vue 中使用。
import _ from 'lodash';
export default {
methods: {
handleInput: _.debounce(function() {
// 防抖逻辑
console.log('Input debounced');
}, 500)
}
}
在模板中绑定事件:
<input @input="handleInput" />
自定义防抖函数
如果不依赖 Lodash,可以手动实现防抖功能。

export default {
methods: {
debounce(func, wait) {
let timeout;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context, args);
}, wait);
};
},
handleInput() {
this.debounce(() => {
console.log('Input debounced');
}, 500)();
}
}
}
使用 Vue 3 的 setup 语法
在 Vue 3 的 Composition API 中,可以更方便地封装防抖逻辑。
import { ref } from 'vue';
export default {
setup() {
const debounce = (func, wait) => {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
func(...args);
}, wait);
};
};
const handleInput = debounce(() => {
console.log('Input debounced');
}, 500);
return { handleInput };
}
}
在 Watcher 中使用防抖
对于 Vue 的 watch,也可以通过防抖优化频繁触发的场景。
export default {
data() {
return {
searchQuery: ''
};
},
watch: {
searchQuery: {
handler: _.debounce(function(newVal) {
console.log('Search query changed:', newVal);
}, 500),
immediate: true
}
}
}
使用第三方库 vue-debounce
vue-debounce 是一个专门为 Vue 设计的防抖库,提供了更简洁的用法。

安装:
npm install vue-debounce
使用:
import VueDebounce from 'vue-debounce';
Vue.use(VueDebounce);
export default {
methods: {
handleInput() {
console.log('Input debounced');
}
}
}
模板中直接使用指令:
<input v-debounce:500ms="handleInput" />
以上方法可以根据项目需求选择最适合的实现方式。






