使用操作DOM的方式实现上拉加载更多。
一、封装hooks,监听页面滑动的位置。
import { onMounted, onUnmounted, ref } from "vue";
export default function () {
//页面是否滑动到最底部
const isReachBottom = ref(false);
//窗口滚动的距离
const scrollTop = ref(0);
//窗口可滚动的高度
const scrollHeight = ref(0);
// 监听窗口的滚动
const scrollListener = () => {
const clientHeight = document.documentElement.clientHeight;
scrollTop.value = document.documentElement.scrollTop;
scrollHeight.value = document.documentElement.scrollHeight;
//窗口可滚动的高度 窗口滚动的距离+页面窗口的位置
if (scrollHeight.value <= scrollTop.value + clientHeight + 1) {
isReachBottom.value = true;
}
};
//页面挂载添加监听
onMounted(() => {
window.addEventListener("scroll", scrollListener);
});
// 离开页面取消监听
onUnmounted(() => {
window.removeEventListener("scroll", scrollListener);
});
return {
isReachBottom,
scrollTop,
scrollHeight,
};
}
二、在页面中引入并使用
<script setup>
import { ref, watch } from 'vue'
import useScroll from "@/hooks/useScroll"
// 当前数据加载到第几页
const homeListPage = ref(1)
//监听页面是否到达底部
const { isReachBottom } = useScroll()
watch(isReachBottom, (newVal) => {
if (newVal) {
homeListPage.value++
//发送网络请求------
isReachBottom.value = false
}
})
</script>
三、改进hooks,可监听DOM元素和window滚动
import { onMounted, onUnmounted, ref } from "vue";
export default function useScroll(elRef) {
let el = window;
const isReachBottom = ref(false);
const clientHeight = ref(0);
const scrollTop = ref(0);
const scrollHeight = ref(0);
const scrollListenerHandle =() => {
if (el === window) {
clientHeight.value = document.documentElement.clientHeight;
scrollTop.value = document.documentElement.scrollTop;
scrollHeight.value = document.documentElement.scrollHeight;
} else {
clientHeight.value = el.clientHeight;
scrollTop.value = el.scrollTop;
scrollHeight.value = el.scrollHeight;
}
// console.log(clientHeight.value, scrollTop.value, scrollHeight.value);
if (clientHeight.value + scrollTop.value >= scrollHeight.value) {
isReachBottom.value = true;
}
}
onMounted(() => {
if (elRef) el = elRef.value;
el.addEventListener("scroll", scrollListenerHandle);
});
onUnmounted(() => {
el.removeEventListener("scroll", scrollListenerHandle);
});
return { isReachBottom, scrollTop };
}
在页面中进行使用
<template>
<div class="home" ref="homeRef">
/*内容*/
</div>
</template>
<script setup>
import { onActivated, ref, watch } from 'vue'
import useScroll from "@/hooks/useScroll"
const homeRef = ref()
//监听页面是否到达底部
const { isReachBottom, scrollTop } = useScroll(homeRef)
watch(isReachBottom, (newVal) => {
if (newVal) {
isReachBottom.value = false
}
})
</script>
在学习coderwhy老师的vue3+pinia时候学到的知识,很好用的。直接引入hooks就可以使用。