I'm trying to use the composition API to create a function that can hide the navbar when scrolling up and show it when scrolling down. I already have this function in vanilla JS, but in Vue3 I'm having difficulty bringing it into the DOM.
In vanilla JS:
let prevScrollpos = window.pageYOffset;
window.onscroll = function () {
console.log('scrolling')
let currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
// @ts-ignore
document.getElementById("navbar").style.top = "0";
} else {
// @ts-ignore
document.getElementById("navbar").style.top = "-65px";
}
prevScrollpos = currentScrollPos;
}
My issue is, in Vue3, I can't seem to register some simple scroll function such as pageYOffset more than once. I am not having any success with the @scroll="function" directive, or with event listeners. At the moment, I'm attempting to use a directive to see the DOM at the base layer, but I don't know how to continually track the scroll position this way either. I would be happy for a fix using a directive but I would also be glad to have a solution that existed just within the Navbar.vue, the Homepage.vue, or the App.vue.
So how do I make Vue3 see the window's scroll position using the Composition API?