javascript - Vue 元素不使用 v-show 隐藏
问题描述
我假设 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>
推荐阅读
- python - 如何在没有任何内置函数的情况下将矩阵乘以 python 中的向量,其中向量和矩阵都是用户的输入
- junit - 如何修复 Kafka 的 JUnit 依赖问题?
- visual-studio - 删除包并重建后找不到程序集?
- bash - 如何将 VAR 从子脚本传递到父脚本运行循环
- java - 从 JVM 中的内存不足异常中恢复并在可能的情况下重置 JVM
- java - WebView 中的视频仅在第一次会话中有效
- for-loop - 如何使用 Ansible 从变量访问标准输出
- c++ - cartToPolar 返回的不同角度不够
- python - 如何结束这个while循环,因为它一直在重复,直到我得到一个列表索引错误
- java - Neo4J java 驱动程序 - org.neo4j.driver.v1.exceptions.UntrustedServerException:服务器未提供产品标识符