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)
}
複製代碼
相關文章
相關標籤/搜索