方式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 = truereturn}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.targetconst scrollTop = scrollElement.scrollTopconst scroll = scrollTop - scrollNum.valuescrollNum.value = scrollTopconsole.log(scrollTop, scroll)if (scrollTop === 0) {// 在顶部,不滚动的情况showNaviBar.value = falsereturn}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