vue实现节流
节流的概念
节流(Throttle)是一种限制函数执行频率的技术,确保函数在一定时间间隔内只执行一次。常用于高频事件(如滚动、输入、鼠标移动等)的性能优化。

在 Vue 中实现节流的方法
使用 Lodash 的 _.throttle
Lodash 提供了现成的节流函数,可直接在 Vue 中使用:

import { throttle } from 'lodash';
export default {
methods: {
handleScroll: throttle(function() {
console.log('Scroll event throttled');
}, 300),
},
mounted() {
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
}
};
自定义节流函数
若不想引入 Lodash,可手动实现节流逻辑:
export default {
methods: {
throttle(func, delay) {
let lastCall = 0;
return function(...args) {
const now = new Date().getTime();
if (now - lastCall < delay) return;
lastCall = now;
func.apply(this, args);
};
},
handleClick() {
this.throttle(() => {
console.log('Button clicked (throttled)');
}, 1000)();
},
},
};
在模板中直接调用节流方法
通过 @click 绑定节流后的方法:
<template>
<button @click="throttledClick">Click Me</button>
</template>
<script>
export default {
methods: {
throttledClick: throttle(function() {
console.log('Throttled click action');
}, 1000),
},
};
</script>
注意事项
- 移除事件监听器:在组件销毁时(
beforeDestroy或onUnmounted)需清理事件监听,避免内存泄漏。 - 箭头函数与
this:若使用自定义节流函数,注意通过func.apply(this, args)绑定正确的上下文。 - Vue 3 组合式 API:在
setup()中可直接使用ref和onMounted实现类似逻辑。
以上方法可根据项目需求选择,推荐优先使用 Lodash 以简化代码。






