vue3中如何使用防抖和节流

1.封装

在src/utils文件夹中新建文件handleDebounce.js,用于封装防抖和节流

// 防抖
export function debounce(fn, delay = 200) {// fn是需要防抖的函数,delay是延迟多少毫秒执行fn
    let timer = null;
    return function () {
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            fn.apply(fn, arguments);
            timer = null;
        }, delay)
    }
}

// 节流
export function throttle(fn, delay = 100) {
    let timer = null;
    return function () {
        if (timer) return;
        timer = setTimeout(() => {
            fn.apply(fn, arguments);
            timer = null;
        }, delay)
    }
}

2.引入使用

防抖
节流


import { debounce,throttle } from "@/utils/handleDebounce";

const clickEvent = debounce(
  () => {
    console.log("防抖");
  }, 800);

const clickEvent2 = throttle(
  () => {
    console.log("节流");
  }, 800);

你可能感兴趣的:(vue3,vue.js,javascript,前端)