本项目博客总结:【前端】Vue项目:旅游App-博客总结
窗口和页面滚动相关链接:【前端】如何判断是页面滚动还是窗口滚动_karshey的博客-CSDN博客
import {
ref } from "vue"
import {
onMounted, onUnmounted } from '@vue/runtime-core';
import {
throttle } from 'underscore'
export default function useScroll(elRef) {
let el = window
const isReachBottom = ref(false)
const isDetailShowTabControl=ref(false)
const clientHeight = ref(0)
const scrollTop = ref(0)
const scrollHeight = ref(0)
// 监听屏幕滚动:这里是窗口的滚动
const scrollListener = throttle(() => {
// 监听窗口的滚动
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
}
if (scrollHeight.value <= scrollTop.value + clientHeight.value) {
console.log('滚动到底部')
isReachBottom.value = true
}
if(scrollTop.value>=540){
isDetailShowTabControl.value=true
}else{
isDetailShowTabControl.value=false
}
// console.log('监听到滚动')
// console.log(scrollTop.value,isDetailShowTabControl.value)
}, 100)
onMounted(() => {
if (elRef) {
el = elRef.value
}
el.addEventListener('scroll', scrollListener)
})
onUnmounted(() => {
el.removeEventListener('scroll', scrollListener)
})
return {
isReachBottom, scrollTop, scrollHeight,clientHeight,isDetailShowTabControl }
}
若不传入elRef,或传入为空,则监听窗口window的滚动。
传入elRef则是对应页面的响应式(此处对页面的定义:设置了高度)。
举个例子:
这里detailRef是detail这个元素对应页面的响应式。
<div class="detail top-page" ref="detailRef">
调用,这里的useScroll监听的是detail页面。
useScroll(detailRef)