【发布时间】:2021-11-15 04:07:50
【问题描述】:
我假设 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,
}
},
【问题讨论】:
-
快速解决方案:只需将您在“滚动”事件处理程序中传递的回调从常规更改为箭头函数。那么关键字“this”的行为就会正确
标签: javascript html vue.js