
image.png
上拉加载的本质是⻚⾯触底,或者快要触底时的动作
判断⻚⾯触底我们需要先了解⼀下下⾯⼏个属性
scrollTop :滚动视窗的⾼度距离 window 顶部的距离,它会随着往上滚动⽽不断增加,初始值是0,它是⼀个变化的值
clientHeight :它是⼀个定值,表示屏幕可视区域的⾼度;
scrollHeight :⻚⾯不能滚动时也是存在的,此时scrollHeight等于clientHeight。scrollHeight表示 body 所有元素的总⻓度(包括body元素⾃身的padding)
综上我们得出⼀个触底公式:
scrollTop + clientHeight >= scrollHeight
简单实现
<script setup>
import { onUnmounted } from 'vue';
const clientHeight = document.documentElement.clientHeight; //浏览器⾼度
const distance = 50; //距离视窗还有50的时候,开始触发;
const fun = () => {
let scrollHeight = document.body.scrollHeight; // 内容高度
let scrollTop = document.documentElement.scrollTop; // 滚动高度
if ((scrollTop + clientHeight) >= (scrollHeight - distance)) {
console.log("开始加载数据");
}
}
// 添加滚动监听
window.addEventListener('scroll', fun);
// 页面卸载清除监听
onUnmounted(() ={
window.removeEventListener('scroll', fun)
});
</script>