vue+typescript怎么设置全局滚动懒加载

如何封装

使用全局容器<div class="scroll-container"></div>包裹内容区vue

提示:我在每一个vue组件内定义了请求接口须要的参数pageNo,和isComplate是否到底的字段,以及preHeight和scrollHeight高度;你可根据你的须要是否增长这几个bash

//定义滚动容器
Vue.prototype.$scrollContainer = function () {
    return (document.querySelector(".scroll-container") as Element)
};
// 定义全局scroll函数
Vue.prototype.$globalScroll = function (that:any) {
    let container = (document.querySelector(".scroll-container") as HTMLElement)
        container.onscroll = function () {
            let offsetH = container.scrollHeight;
            let winH = container.offsetHeight;
                winH = Math.ceil(winH);
            let scrollH = (container as Element).scrollTop;
            //滚动触发的条件
            if (offsetH <= winH + scrollH) {
                //销毁组件时不触发滚动事件
                if(!that) return 
                //避免数据过多滚动加载连续请求
                that.$scrollContainer().scrollTop = that.preHeight - 200
                that.scrollHeight =  !that.empty ? that.$scrollContainer().scrollHeight : 0
                //避免请求到底了从新滚动还会加载;到底了再也不请求
                if (!that.isComplate && that.preHeight < that.scrollHeight) {
                    that.preHeight =  that.$scrollContainer().scrollHeight;
                    that.pageNo = that.pageNo + 1
                    //加载请求新的数据
                    that.getData()
                }
            }
        };
};
复制代码

如何使用

在每一个vue组件的mounted生命周期内调用函数

mounted(){
    this.$globalScroll(this)
}
复制代码
相关文章
相关标签/搜索