gpt4 book ai didi

javascript - Vue 元素不通过 v-show 隐藏

转载 作者:行者123 更新时间:2023-12-02 18:27:18 28 4
gpt4 key购买 nike

我假设 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,
}
},

最佳答案

您需要通过将methods block 中定义的方法之一绑定(bind)到窗口的滚动事件来处理scroll 事件。在您的情况下,传递给 scroll 事件监听的 callback 函数将无法访问 vue 实例,因此它不会更新 react 属性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>

关于javascript - Vue 元素不通过 v-show 隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69969394/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com