监听页面滚动到底部和页面滚动距离

886 阅读1分钟
监听有方法要放在主页面中,不能放在组件中,切记,监听页面滚动到底部放回true,发请求获取新数据,监听页面滚动距离返回值,滚动一定距离后显示吸顶组件
在src中的hooks文件夹下创建useScroll.js文件
import { ref } from "vue";
import { onActivated, onDeactivated, onMounted, onUnmounted } from "vue";
// npm install underscore
// 节流,需要先安装
import { throttle } from "underscore";
export default function useScrool() {
  // 是否滚动到底部
  const isReachBottom = ref(false);
  // 当前滚动高度
  const scrollTop = ref(0);
  //页面总高度
  const scrollHeight = ref(0);
  // 屏幕高度
  const clientHeight = ref(0);
  // 监听window创建的滚动
  // 节流
  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);
  });
  // 使用keep-alive缓存组件活跃时
  onActivated(() => {
    window.addEventListener("scroll", scrollListenerHandler);
  });
  //离开页面移除监听
  onUnmounted(() => {
    window.removeEventListener("scroll", scrollListenerHandler);
  });
  // 使用keep-alive缓存组件销毁时
  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) {
    // 发请求加载更多数据并且isReachBottom设置为false
    //homeStore.getHouseList()为发请求,需替换为自己的方法
    homeStore.getHouseList().then(() => {
      isReachBottom.value = false;
    }); //请求示例
  }
});

// 页面滚动距离达到100后显示吸顶搜索框
const showSearchBar = computed(() => {
  return scrollTop.value >= 100;
});
html
//通过判断showSearchBar动态显示吸顶组件
<searchBar v-if="showSearchBar" />