vue实现防抖
Vue 实现防抖的方法
防抖(Debounce)是一种常用的性能优化技术,用于限制函数在短时间内被频繁调用。Vue 中可以通过以下几种方式实现防抖。
使用 Lodash 的 debounce 方法
Lodash 提供了现成的 debounce 函数,可以直接在 Vue 中使用。
import { debounce } from 'lodash';
export default {
methods: {
handleInput: debounce(function() {
// 防抖逻辑
console.log('Input debounced');
}, 500),
},
};
自定义防抖函数
如果不想引入 Lodash,可以手动实现一个简单的防抖函数。
export default {
methods: {
debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
},
handleInput() {
const debouncedFn = this.debounce(() => {
console.log('Input debounced');
}, 500);
debouncedFn();
},
},
};
在模板中直接使用防抖
可以通过在模板中直接调用防抖函数来实现。
<template>
<input @input="debouncedHandleInput" />
</template>
<script>
import { debounce } from 'lodash';
export default {
methods: {
handleInput() {
console.log('Input debounced');
},
},
created() {
this.debouncedHandleInput = debounce(this.handleInput, 500);
},
};
</script>
使用 Vue 自定义指令
通过自定义指令实现防抖功能,可以复用性更高。
Vue.directive('debounce', {
inserted(el, binding) {
let timeoutId;
el.addEventListener('input', () => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
binding.value();
}, binding.arg || 500);
});
},
});
// 使用方式
<template>
<input v-debounce:300="handleInput" />
</template>
以上方法可以根据具体需求选择适合的方式实现防抖功能。







