vue3+ts 节流防抖全局使用

1.在utils下创建一个ts文件夹 随便你叫什么 。

import { ref, watchEffect } from 'vue';

export const useThrottleDebounce = () => {
    const throttleTimer = ref<any>(null);
    const debounceTimer = ref<any>(null);

    const throttle = (fn: Function, delay = 500) => {
        if (throttleTimer.value) {
            return;
        }
        throttleTimer.value = setTimeout(() => {
            fn();
            throttleTimer.value = null;
        }, delay);
    };
    
    const debounce = (fn: Function, delay = 500) => {
        clearTimeout(debounceTimer.value);
        debounceTimer.value = setTimeout(() => {
            fn();
        }, delay);
    };

    const clearThrottle = () => {
        clearTimeout(throttleTimer.value);
        throttleTimer.value = null;
    };

    const clearDebounce = () => {
        clearTimeout(debounceTimer.value);
        debounceTimer.value = null;
    };

    return {
        throttle,
        debounce,
        clearThrottle,
        clearDebounce,
    };
};

2. 在vue组件中使用,防抖节流看情况用哈

import { useThrottleDebounce } from "@/utils/throttle-debounce";
 
//setup 里面 
    const { throttle, debounce, clearThrottle, clearDebounce } =useThrottleDebounce();//引入方法使用

    const searchGame = (name) => {
      debounce(() => {
      这里是你的逻辑代码,其实也就是调用接口的地方
      });
    };