内容:通过监听scrollTop的值进行显示搜索(菜单)组件/进行数据的加载
1.了解三个与该内容相关的属性
- document.documentElement.scrollTop
- 该属性就是获取已经滚动了的高度
- document.documentElement.scrollHeight
- 获取window的总高度,就是最外层页面内容的高度
- document.documentElement.clientHeight
- 获取客户端窗口大小
2.编写一个scrollListener函数
// 2.通过返回参数进行 监听window的滚动来加载数据
export default function scrollListener(elRef) {
let el = window;
const scrollTop = ref(0);
const scrollHeight = ref(0);
const clientHeight = ref(0);
const isReach = ref(false);
const scroll = throttle(() => {
if (el === window) {
scrollTop.value = document.documentElement.scrollTop;
scrollHeight.value = document.documentElement.scrollHeight;
clientHeight.value = document.documentElement.clientHeight;
} else {
scrollTop.value = el.scrollTop;
scrollHeight.value = el.scrollHeight;
clientHeight.value = el.clientHeight;
}
if (scrollTop.value + clientHeight.value >= scrollHeight.value - 50) {
console.log('滚动到底部了');
isReach.value = true;
}
}, 100);
onMounted(() => {
if (elRef) el = elRef.value;
el.addEventListener('scroll', scroll);
});
onUnmounted(() => {
el.removeEventListener('scroll', scroll);
});
return { isReach, scrollTop, scrollHeight, clientHeight };
}
3.通过监听scrollTop的值,可以实现当页面滚动到指定的位置后显示搜索(菜单)组件
4.通过监听isReach的值,判断当前页面是否滚动到底部,若滚动到底部则进行数据的请求
听了coderwhy老师的课做的笔记