后端一次性返回 十万条数据——分页加载

239 阅读1分钟

分页加载

滚动到底部时再加载下一页的数据

let data = [];
// 模拟十万条数据
for (let i = 0; i < 10000; i++) {
    data.push({ url: '' })
}
        
class RenderEl {
    constructor(options) {
        const { el, data, page = 1, size = 20, fn } = options;
        this.el = el || 'body';
        this.data = data || [];
        this.page = page;
        this.size = size;
        this.total = this.data.length;
        this.totalPage = Math.ceil(this.total / this.size);
        this.winH = $(window).innerHeight();
        this.elFn = typeof fn === "function" ? fn : '';
    }
    // 初始化
    init() {
        this._render()
        this._scroll()
    }
    // 渲染数据
    _render() {
        const start = (this.page - 1) * this.size;
        const end = this.page * this.size - 1;
        const newData = this.data.slice(start, end + 1);
        newData.forEach((item, index, arr) => {
            this.elFn(item, start + index, arr)
        })
    }
    // 监听滚动到底部
    _scroll() {
        $(document).scroll(() => {
            const h = $(this.el).innerHeight() - $(document).scrollTop();
            if (h <= this.winH && this.page < this.totalPage) {
                this.page++;
                this._render();
            }
        })
    }
}

const renderEl = new RenderEl({
    el: '#lazyBox',
    data,
    fn: (item, index, arr) => {
        return $('#lazyBox').append(`
            <div>
                <h1>${index+1}</h1>
                <img data-index="${index}" src="${item.url}" class="image">
            </div>
        `);
    }
});
renderEl.init();
<div id="lazyBox" class="lazy-box"></div>
.lazy-box {
    display: flex;
    flex-direction: column;
}

.image {
    width: 192px;
    height: 120px;
    margin-bottom: 15px;
}

使用了