监听有方法要放在主页面中,不能放在组件中,切记,监听页面滚动到底部放回true,发请求获取新数据,监听页面滚动距离返回值,滚动一定距离后显示吸顶组件
在src中的hooks文件夹下创建useScroll.js文件
import { ref } from "vue";
import { onActivated, onDeactivated, onMounted, onUnmounted } from "vue";
import { throttle } from "underscore";
export default function useScrool() {
const isReachBottom = ref(false);
const scrollTop = ref(0);
const scrollHeight = ref(0);
const clientHeight = ref(0);
const scrollListenerHandler = throttle(() => {
scrollTop.value = document.documentElement.scrollTop;
scrollHeight.value = document.documentElement.scrollHeight;
clientHeight.value = document.documentElement.clientHeight;
if (scrollHeight.value <= scrollTop.value + clientHeight.value) {
isReachBottom.value = true;
}
}, 200);
onMounted(() => {
window.addEventListener("scroll", scrollListenerHandler);
});
onActivated(() => {
window.addEventListener("scroll", scrollListenerHandler);
});
onUnmounted(() => {
window.removeEventListener("scroll", scrollListenerHandler);
});
onDeactivated(() => {
window.removeEventListener("scroll", scrollListenerHandler);
});
return { isReachBottom, scrollTop, scrollHeight, clientHeight };
}
使用
import { computed, watch } from "vue";
import useScroll from "@/hooks/useScroll";
const { isReachBottom, scrollTop } = useScroll();
watch(isReachBottom, (newValue) => {
if (newValue) {
homeStore.getHouseList().then(() => {
isReachBottom.value = false;
});
}
});
const showSearchBar = computed(() => {
return scrollTop.value >= 100;
});
html
//通过判断showSearchBar动态显示吸顶组件
<searchBar v-if="showSearchBar" />