IntersectionObserver 實現(xiàn)滾動加載

什么是IntersectionObserver

IntersectionObserver是瀏覽器提供的一個API,它可以用來監(jiān)聽元素是否進入了設(shè)備的可視區(qū)域之內(nèi),而不需要頻繁的計算來做這個判斷。在以前我們常用onscroll跟setTimeOut等對頁面進行監(jiān)聽,缺點是onscroll計算量大會導(dǎo)致性能問題,setTimeOut時間差的問題。因此瀏覽器提供了這個api提供我們使用。

Api介紹

var observer = new IntersectionObserver(callback,options); IntersectionObserver支持兩個參數(shù):
callback是當被監(jiān)聽元素的可見性變化時,觸發(fā)的回調(diào)函數(shù)
options是一個配置參數(shù),可選,有默認的屬性值

實現(xiàn)滾動加載

在.vue文件中

<templete>
<div class="card-list" ref="obtain">
                <div v-for="(item, index) in cardList" :key="index" :oItem="item" :oIndex="index" ></div>
                <p class="blank" ></p>
                <p class="lazy"></p>
            </div>
</templete>
data() {
 cardList: []
},
methods:{
scrollPageList() {
            const blank = document.querySelector('.blank');  // 判斷是否存在判斷是佛到底部的標志
            const lazyDom = document.querySelector('.lazy');  // 判斷是否超出可視區(qū)的標志
            if(!blank) return; 
            this.observer = new IntersectionObserver(([entry]) => { //  創(chuàng)建一個IntersectionObserver對象
                if (entry && entry.isIntersecting) {   // 判斷是否進入了可視區(qū)
                    lazyDom.style.display = 'block'; // 進去可視區(qū)以后
                        setTimeout(() => {
                        this.pageNum++;  // 頁數(shù)+1
                          this.getnextPageData(); // 請求下一頁的方法
                    }, 300);
                } else {
                    lazyDom.style.display = 'none';  // 離開可視區(qū)以后
                }
            })
            this.observer.observe(blank);
        },
}]

在created生命周期中進行初始化

created(){
this.getnextPageData();
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容