vue项目实现无限加载--scroll事件+节流+防抖

1,187 阅读1分钟

1.给页面绑定滚动事件

 // 先给页面注册滚动事件-加上节流
 //第三个参数必须为true,节流暂且看成普通的回调函数
document.addEventListener('scroll', throttle(this.scroll, 300), true)

2.写事件的回调函数

/ 滚动事件-分页获取数据
scroll() {
//整体的滚动计算--加上节流
// 垂直滚动距离
let scrollTop = document.documentElement.scrollTop || document.body.scrollTop; 
// 保存最大滚动的距离
if (scrollTop > this.scrollTop) this.scrollTop = scrollTop;
// 可视高度 
let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
// 整个滚动的高度
let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
// 距底部一屏的距离,发请求获取数据--且数据拿完后,不再发请求--(this.isShow为true时表示数据拿完了)
if (scrollHeight - (this.scrollTop+clientHeight) < clientHeight && !this.isShow) {
    // 加上防抖后的请求
    this.debGet(this);
}
},

 // 防抖请求
debGet: debounce((that) => {
   that.currPage = that.currPage + 1; //获取下一页的数据
   that.getShopsList()
}, 300),

3.防抖,节流函数-(网上抄的,仅供学习)

// 工具库

// 节流函数
/**
 * @param fun 要防抖的函数
 * @param delay 防抖的时间间隔
*/
export function throttle(fun, delay) {
    let last, deferTimer
    return function (args) {
        let that = this
        let _args = arguments
        let now = +new Date()
        if (last && now < last + delay) {
            clearTimeout(deferTimer)
            deferTimer = setTimeout(function () {
                last = now
                fun.apply(that, _args)
            }, delay)
        } else {
            last = now
            fun.apply(that, _args)
        }
    }
}

// 防抖函数
/*
    @param fun 要防抖的函数
    @param delay 防抖的时间间隔
*/
export function debounce(fun, delay) {
    return args => {
        clearTimeout(fun.id)
        fun.id = setTimeout(() => {
            fun.call(this, args)
            // fun(args)
        }, delay)
    }
}