厦门网站建设114,帮人做任务的网站,蒙自网站建设,网站建设与运营财务报表一、封装 1.这个是在vue3环境下的封装 2.整体思路#xff1a; 2.1传入一个elRef#xff0c;其实就是一个使用页面的ref。 2.2也可以不传elRef#xff0c;则默认滚动的是window。
import { onMounted, onUnmounted, ref } from vue;
import { throttle } from underscore;ex…一、封装 1.这个是在vue3环境下的封装 2.整体思路 2.1传入一个elRef其实就是一个使用页面的ref。 2.2也可以不传elRef则默认滚动的是window。
import { onMounted, onUnmounted, ref } from vue;
import { throttle } from underscore;export default function useScroll(elRef) {let el windowconst isReachBottm ref(false)const clientHeight ref(0)const scrollTop ref(0)const scrollHeight ref(0)const scrollListenerHandler throttle(() {if(el window) {clientHeight.value document.documentElement.clientHeight; // 当前浏览器窗口的“可视区域”的高度scrollTop.value document.documentElement.scrollTop; // 用于获取文档通常是 HTML 文档相对于其顶部的滚动距离scrollHeight.value document.documentElement.scrollHeight; // 获取到的是整个 HTML 文档的高度包括所有可见和不可见的内容即滚动条可滚动的总高度}else {clientHeight.value el.clientHeight;scrollTop.value el.scrollTop;scrollHeight.value el.scrollHeight;}if (clientHeight.value scrollTop.value scrollHeight.value) {isReachBottm.value true}}, 100)onMounted(() {if(elRef) el elRef.valueel.addEventListener(scroll, scrollListenerHandler)})onUnmounted(() {el.removeEventListener(scroll, scrollListenerHandler)})return { isReachBottm, clientHeight, scrollTop, scrollHeight }
}二、使用
import { watch, ref, computed } from vue;
import useScroll from /hooks/useScroll;
const { isReachBottm, clientHeight, scrollTop, scrollHeight } useScroll()watch(isReachBottm, (newValue) {if (newValue) {homeStore.fetchHouselistData()isReachBottm.value false}
})const isShowSearchBar computed(() {return scrollTop.value 350
})