Im under the assumption that v-show will show/hide elements based on its passed data.
For some reason, my element will not hide dynamically when v-show is false. When I manually change the variable (showNav) to false, it will be hidden on page load so it seems to functioning properly.
My variable (showNav) depends on scroll. When scroll up, it is set to true, when scroll down it is set to false. I'd like my nav bar to hide on scroll down but that is not happening.
The scroll behavior is behaving properly. Both are properly changing my v-show variable (showNav) to either true or false but the element remains visible at all times.
HTML template
<template>
<div id="home-page">
<Navbar id="navbar" v-show="showNav" :class="{change_background: scrollPosition > 50}" />
</div>
</template>
JS
mounted() {
window.addEventListener('scroll', function(){
// detects new state and compares it with the old one
if ((document.body.getBoundingClientRect()).top > this.scrollPos) {
this.showNav = true;
console.log(this.showNav);
}
else
{
this.showNav = false;
console.log(this.showNav);
}
// saves the new position for iteration.
this.scrollPos = (document.body.getBoundingClientRect()).top;
})
},
data() {
return {
scrollPosition: null,
scrollPos: 0,
showNav: true,
}
},
You need to handle the scroll
events by binding one of the methods defined within the methods
block to the scroll event of the window. In your case the callback
function passed to the scroll
event listen will not have access to the vue instance
and hence it will not update the reactive properties of vuejs
. See the working sample below.
new Vue({
el: "#app",
data() {
return {
scrollPosition: null,
scrollPos: 0,
showNav: true,
}
},
mounted() {
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll); // To avoid memory leakage
},
methods: {
handleScroll(event) {
// detects new state and compares it with the old one
if ((document.body.getBoundingClientRect()).top > this.scrollPos) {
this.showNav = true;
console.log(this.showNav);
} else {
this.showNav = false;
console.log(this.showNav);
}
// saves the new position for iteration.
this.scrollPos = (document.body.getBoundingClientRect()).top;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app" style="min-height: 1000px;">
<span v-show="showNav">You are trying to hide me</span>
</div>