基於 IntersectionObserver 異步監聽方法,實現無線信息流下拉加載,
https://developer.mozilla.org/zh-CN/docs/Web/API/IntersectionObserver
<template>
<div id="app">
<!-- 1. 設置容器元素,view-list-->
<div class="view-list">
<!-- 2. 循環一個列表,新數據進行追加,下面增加一個loading條-->
<div class="item" v-for="(item,index) in itemData" :key="index">賬號ID:{{index}}</div>
<div class="item" id="loading">加載中</div>
</div>
</div>
</template>
<script>
export default {
name: 'App',
components: {
},
data(){
return {
itemData:[]
}
},
methods:{
// 獲取隨機數
getRange(){
let id = new Date().getTime();
return Math.random()*id;
},
// 觸發監聽回調
loadList(status){
status = status[0];
let isShow = status.isIntersecting;
if(isShow){
console.log("加載中 ---- ");
for(let i = 4;i>=0;i--){
this.itemData.push({id:this.getRange()})
}
}else {
console.log('不加載');
}
}
},
created() {
// 3. 初始化循環渲染的列表
for(let i = 4;i>=0;i--){
this.itemData.push({id:this.getRange()})
}
},
mounted() {
// 4. 掛載時,獲取列表的容器元素,然后設置監聽
// 使用官方提供的新接口:https://developer.mozilla.org/zh-CN/docs/Web/API/IntersectionObserver
/**
* callback : 回調函數,可見時 和 不可見時,都觸發
* options :配置參數,
* root :根元素,默認是視圖
* threshold : 交叉比例。也就是在跟元素出現的比例
*/
// 5. 初始化觀察對象
let io = new IntersectionObserver(this.loadList, {});
// 6. 獲取被監聽元素
let viewList = document.getElementById('loading');
// 7. 在觀察對象上,監聽 6 中獲取的對象
io.observe(viewList);
},
}
</script>
<style>
.view-list{
width: 100%;
height: 500px;
margin:20px 0;
overflow-x: scroll;
background-color: rgba(0, 0, 255, 0.25);
}
.item{
height: 50px;
border:1px gray solid;
margin-bottom: 10px;
}
</style>