方式1. 使用useScroll方式
import { useScroll } from '@vueuse/core'
setup() {
const showNaviBar = ref(true)
const { arrivedState } = useScroll(document.querySelector('.body'), {
onScroll: (e) => {
console.log(arrivedState.top, arrivedState.bottom)
if (arrivedState.top) {// 在顶部
showNaviBar.value = true
return
}
if (arrivedState.bottom) {// 到底
showNaviBar.value = false
} else {
showNaviBar.value = true// 其它情况..
}
},
})
return {
showNaviBar,
}
}
方式2. 直接监听dom的scroll事件
import { ref, onBeforeUnmount, onMounted } from '@vue/composition-api'
setup() {
const showNaviBar = ref(true)
const scrollNum = ref(0)
const handleScroll = (e) => {
const scrollElement = e.target
const scrollTop = scrollElement.scrollTop
const scroll = scrollTop - scrollNum.value
scrollNum.value = scrollTop
console.log(scrollTop, scroll)
if (scrollTop === 0) {// 在顶部,不滚动的情况
showNaviBar.value = false
return
}
if (scroll >= 0) { // 在滚动时,向下
showNaviBar.value = false
} else {// 在滚动时,向上
showNaviBar.value = true
}
}
onMounted(() => {
const scrollElement = document.querySelector('.body')
scrollElement.addEventListener('scroll', handleScroll)
})
onBeforeUnmount(() => {
const scrollElement = document.querySelector('.body')
scrollElement.removeEventListener('scroll', handleScroll)
showNaviBar.value = true
})
return {
showNaviBar,
}
}
handleScroll 打印日志: down
2582 23
2601 19
2614 13
2623 2
handleScroll 打印日志: up
2787 -13
2773 -14
2728 -8
2724 -4