vue中节流的实现
节流的基本概念
节流(Throttle)是一种限制函数执行频率的技术,确保函数在一定时间间隔内只执行一次。适用于高频触发的事件(如滚动、输入、窗口调整等),避免性能问题。
使用 Lodash 实现节流
Lodash 提供了 _.throttle 方法,可直接用于 Vue 组件:

-
安装 Lodash:
npm install lodash -
在 Vue 组件中引入并使用:

import { throttle } from 'lodash'; export default { methods: { handleScroll: throttle(function() { console.log('Scroll event throttled'); }, 200), // 200ms 内只执行一次 }, mounted() { window.addEventListener('scroll', this.handleScroll); }, beforeDestroy() { window.removeEventListener('scroll', this.handleScroll); } };
手动实现节流函数
若不想依赖 Lodash,可自定义节流函数:
function throttle(func, delay) {
let lastCall = 0;
return function(...args) {
const now = new Date().getTime();
if (now - lastCall >= delay) {
func.apply(this, args);
lastCall = now;
}
};
}
export default {
methods: {
handleInput: throttle(function(event) {
console.log('Input throttled:', event.target.value);
}, 300),
},
template: `<input @input="handleInput" />`,
};
在 Vue 3 中使用 Composition API
通过 ref 和 onMounted 结合节流:
import { ref, onMounted, onUnmounted } from 'vue';
export default {
setup() {
const handleScroll = throttle(() => {
console.log('Throttled scroll');
}, 200);
onMounted(() => window.addEventListener('scroll', handleScroll));
onUnmounted(() => window.removeEventListener('scroll', handleScroll));
return { handleScroll };
},
};
注意事项
- 清除监听器:在组件销毁时移除事件监听,避免内存泄漏。
- 时间间隔选择:根据场景调整节流时间(如搜索建议可用 300ms,滚动事件可用 100ms)。
- 避免箭头函数:若需访问 Vue 实例的
this,使用普通函数而非箭头函数。
通过上述方法,可灵活实现 Vue 中的节流功能,优化高频事件性能。






