vue中实现节流函数
使用 Lodash 的 _.throttle 方法
安装 Lodash 并导入 throttle 方法:
npm install lodash
在 Vue 组件中使用:
import { throttle } from 'lodash';
export default {
methods: {
handleClick: throttle(function() {
console.log('Throttled click');
}, 1000)
}
}
自定义节流函数实现
手动实现一个节流函数:
function throttle(func, delay) {
let lastCall = 0;
return function(...args) {
const now = new Date().getTime();
if (now - lastCall < delay) return;
lastCall = now;
return func.apply(this, args);
};
}
在 Vue 中的使用方式:
export default {
methods: {
handleScroll: throttle(function() {
console.log('Scrolling throttled');
}, 200)
},
mounted() {
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
}
}
使用 Vue 自定义指令实现
创建全局节流指令:
Vue.directive('throttle', {
inserted(el, binding) {
const [func, delay] = binding.value;
let timer = null;
el.addEventListener('click', () => {
if (timer) return;
func();
timer = setTimeout(() => {
timer = null;
}, delay);
});
}
});
使用方式:
<button v-throttle="[handleClick, 1000]">Click Me</button>
使用 Composition API 实现
在 Vue 3 中使用 setup 函数:
import { ref } from 'vue';
export default {
setup() {
const count = ref(0);
const throttledIncrement = throttle(() => {
count.value++;
}, 1000);
return {
count,
throttledIncrement
};
}
}
注意事项
节流函数的时间间隔需要根据实际场景调整,过短可能达不到效果,过长会影响用户体验。
事件监听器需要在组件销毁时移除,避免内存泄漏。
对于需要访问组件实例的情况,需要使用 function 而非箭头函数来保持正确的 this 绑定。







