무한 스크롤
많은 사람들이 무한 스크롤, 그냥 생각 로드 바닥 있지만, 특정 길이의로드 페이지가 폭발합니다! !
사실상 무제한의 부하가 거의 무제한입니다!
페이지에만 보이는 요소를 렌더링 페이지가 진정한 무한 스크롤을 달성하기 전에 노드를 차지하지 않습니다 볼 수 없습니다.
![무한 스크롤 -2](https://images.cnblogs.com/cnblogs_com/lihao97/1612453/o_19121211454620191212_191047_38.jpg)
IntersectionObserver 모니터 요소 볼을에 반사
달성 할 수있다 :
1. 触顶:移除下面,渲染上面,解除顶部占位
2. 触底:移除上面,渲染下面,增加顶部占位
구현 기술 :
1. 只修改一个变量达到效果。
2. 用计算属性动态得出该渲染什么。
3. `threshold`使用`0.0000001`,判断`intersectionRatio > 0.01`比较稳(能保证真正的可见)。
4. end元素,向上相对定位,实现预加载(提前触底)。
구현 코드 :
보기 층
<template>
<div class="infinity-sroll-container">
<div :style="{ paddingTop: (showStart - 1) * 200 + 'px' }">
<div data-site="start" ref="start"></div>
<div
class="item"
v-for="(n, i) in showList"
:key="i"
:style="{backgroundColor: colors[n % 10]}"
>
{{n}}
</div>
<div class="end" data-site="end" ref="end"></div>
</div>
</div>
</template>
논리 계층
export default {
data() {
return {
showStart: 1,
colors: [
'#CCCC33',
'#CCCCCC',
'#FFFFCC',
'#0099FF',
'#33CC99',
'#FFFFFF',
'#ff9900',
'#99CC33',
'#99CCFF',
'#CC9999'
]
};
},
computed: {
showList() {
const result = [];
for (let i = 0; i < 20; i += 1) {
result.push(this.showStart + i);
}
return result;
}
},
mounted() {
const io = new IntersectionObserver((entries) => {
if (entries[0].intersectionRatio > 0.001) {
if (entries[0].target.dataset.site === 'end') {
this.showStart += 10;
} else {
this.showStart = (this.showStart - 10 <= 1) ? 1 : (this.showStart - 10);
}
}
}, {
threshold: [0.000001],
});
io.observe(this.$refs.start);
io.observe(this.$refs.end);
}
};
레이어 스타일
// lang="scss" scoped
.infinity-sroll-container{
.item {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 200px;
font-weight: bold;
}
.end {
position: relative;
top: -400px;
}
}