实现思路:
我创建了一个通用的防抖函数 debounce
和节流函数 throttle
。然后,在组件中使用 ref
来保持防抖和节流函数的引用,并在 onMounted
生命周期钩子中初始化这些函数。
遇到的问题:
必须使用ref或reactive存储防抖和节流的引用,(一开始我的问题出在了 debounce
函数的使用上,Vue 3 的 script setup
语法中的函数会在每次组件重新渲染时重新定义,从而导致 debounce
函数无法保持稳定的引用。为了解决这个问题,使用 Vue 3 提供的 ref
来保持稳定的引用)
代码:
<template>
<!-- 组件模板 -->
</template>
<script setup>
import { ref, onMounted } from 'vue';
// 通用的防抖函数
function debounce(func, delay) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
// 通用的节流函数
function throttle(func, delay) {
let isThrottled = false;
return function (...args) {
if (!isThrottled) {
func.apply(this, args);
isThrottled = true;
setTimeout(() => {
isThrottled = false;
}, delay);
}
};
}
// 在组件内使用防抖和节流函数
const debouncedFunction = ref(null);
const throttledFunction = ref(null);
onMounted(() => {
// 防抖函数示例
debouncedFunction.value = debounce(() => {
// 要防抖执行的逻辑
console.log('Debounced function executed.');
}, 1000);
// 节流函数示例
throttledFunction.value = throttle(() => {
// 要节流执行的逻辑
console.log('Throttled function executed.');
}, 1000);
});
// 在需要的地方触发防抖函数
function triggerDebounce() {
debouncedFunction.value();
}
// 在需要的地方触发节流函数
function triggerThrottle() {
throttledFunction.value();
}
</script>
<style>
/* 样式代码 */
</style>