所以我只是想让我的基本 Vue 导航栏功能正常工作,例如更改滚动时的类(效果很好)和更改调整大小时的类,这对我来说有点麻烦。
这是我的<template>
的内容标签:
<nav class="navbar is-fixed-top navbar-max">
{{windowWidth}}
</nav>
...以及我的<script>
的相关内容标签:
export default {
name: "Navbar",
data () {
return {
windowWidth: window.innerWidth
}
},
created () {
window.addEventListener('resize', this.onResize);
},
mounted () {
this.windowWidth = window.innerWidth
},
beforeDestroy () {
window.removeEventListener('resize', this.onResize);
},
methods: {
onResize() {
let navbar = document.querySelector(".navbar");
if (this.windowWidth > 768) {
console.log(this.windowWidth),
navbar.classList.remove("nav-mobile"),
navbar.classList.add("nav-desktop")
}
else {
console.log(this.windowWidth),
navbar.classList.remove("nav-desktop"),
navbar.classList.add("nav-mobile")
}
}
}
}
我的问题真的很奇怪 - 我所有的console.log()
输出正确的宽度, {{windowWidth}}
也是如此在导航栏中,甚至添加和删除类也有效!只是改变的类似乎没有任何效果,直到 windowWidth = 1024
我不知道为什么......
有什么帮助吗?
干杯:)
最佳答案
挂载后您从未设置this.windowWidth
。
只需添加以下内容:
onResize() {
this.windowWidth = window.innerWidth // add this line
...
}
我还想指出,您想要实现的目标(移动设备和桌面设备上的不同导航栏样式)是非常可行的,无需任何 vue-/js-magic 使用 CSS @media-queries .
如果你仍然想用 vue 来做,你应该用 vue 的方式来做: 创建一个像这样的计算方法:
computed: {
isMobile() {
return this.windowWidth <= 768
}
}
然后使用 class-binding 直接在导航标签上更新类.
关于javascript - Vue 在与窗口宽度相关的条件下表现得很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63053870/