我假设 v-show 将根据传递的数据显示/隐藏元素。
由于某种原因,当 v-show 为 false 时,我的元素不会动态隐藏。当我手动将变量 (showNav) 更改为 false 时,它将在页面加载时隐藏,因此它似乎可以正常运行。
我的变量(showNav)取决于滚动。当向上滚动时,它设置为 true,当向下滚动时,它设置为 false。我希望我的导航栏在向下滚动时隐藏,但这没有发生。
滚动行为表现正常。两者都正确地将我的 v-show 变量 (showNav) 更改为 true 或 false,但该元素始终保持可见。
HTML模板
<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,
}
},
你需要处理scroll
通过绑定中定义的方法之一来事件methods
阻止窗口的滚动事件。在你的情况下callback
函数传递给scroll
事件监听将无权访问vue instance
因此它不会更新vuejs
。请参阅下面的工作示例。
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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)