vue项目实现防抖
Vue 项目中实现防抖的方法
防抖(Debounce)是一种限制函数频繁调用的技术,确保函数在最后一次调用后的一段时间内不再被触发。以下是几种在 Vue 项目中实现防抖的方法:
使用 Lodash 的 _.debounce 方法
Lodash 提供了 _.debounce 方法,可以直接在 Vue 组件中使用。
import _ from 'lodash';
export default {
methods: {
handleInput: _.debounce(function() {
// 防抖逻辑
console.log('Input debounced');
}, 500),
},
};
自定义防抖函数
如果不想引入 Lodash,可以手动实现一个简单的防抖函数。
function debounce(func, wait) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(this, args);
}, wait);
};
}
export default {
methods: {
handleInput: debounce(function() {
// 防抖逻辑
console.log('Input debounced');
}, 500),
},
};
在模板中直接使用防抖
可以在模板中直接调用防抖函数,但需要注意函数的绑定。
<template>
<input @input="debouncedHandleInput" />
</template>
<script>
export default {
methods: {
debouncedHandleInput: debounce(function() {
// 防抖逻辑
console.log('Input debounced');
}, 500),
},
};
</script>
使用 Vue 3 的 setup 语法
在 Vue 3 的 Composition API 中,可以更方便地使用防抖。
import { ref } from 'vue';
import { debounce } from 'lodash';
export default {
setup() {
const handleInput = debounce(() => {
// 防抖逻辑
console.log('Input debounced');
}, 500);
return { handleInput };
},
};
在生命周期钩子中清理防抖
为了避免内存泄漏,需要在组件销毁时清理防抖的定时器。
export default {
data() {
return {
debouncedHandleInput: null,
};
},
created() {
this.debouncedHandleInput = debounce(function() {
// 防抖逻辑
console.log('Input debounced');
}, 500);
},
beforeUnmount() {
if (this.debouncedHandleInput) {
this.debouncedHandleInput.cancel();
}
},
};
以上方法可以根据项目需求选择适合的方式实现防抖功能。







