VUE使用防抖和节流,避免重复触底加载和点击

1.可以在utils文件夹中新建一个common.js文件

 // 防抖
 export const Debounce = (fn, t) => {
    let delay = t || 500;
    let timer;
    console.log(fn)
    console.log(typeof fn)
    return function () {
        let args = arguments;
        if(timer){
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            timer = null;
            fn.apply(this, args);
        }, delay);
    }
 };


 // 节流
 export const Throttle = (fn, t) => {
    let last;
    let timer;
    let interval = t || 500;
    return function () {
        let args = arguments;
        let now = +new Date();
        if (last && now - last < interval) {
            clearTimeout(timer);
            timer = setTimeout(() => {
                last = now;
                fn.apply(this, args);
            }, interval);
        } else {
            last = now;
            fn.apply(this, args);
        }
    }
 };

2.在需要使用的组件中引入

 import { Debounce } from "@/utils/common.js";

3.使用

 methods:{
    getSearchGoods: Debounce(function () {
      
    },1000),
 }

上一篇:HTML5基本特性和新功能


下一篇:Java-LinkedList