Javascript 与窗口宽度相关的条件下,Vue表现异常
因此,我只是想让我的基本Vue导航栏功能正常工作,比如在滚动时更改类(工作正常)和在调整大小时更改类,这让我有点麻烦 以下是我的Javascript 与窗口宽度相关的条件下,Vue表现异常,javascript,css,vue.js,Javascript,Css,Vue.js,因此,我只是想让我的基本Vue导航栏功能正常工作,比如在滚动时更改类(工作正常)和在调整大小时更改类,这让我有点麻烦 以下是我的标签的内容: <nav class="navbar is-fixed-top navbar-max"> {{windowWidth}} </nav> export default { name: "Navbar", data () { return { win
标签的内容:
<nav class="navbar is-fixed-top navbar-max">
{{windowWidth}}
</nav>
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()
都输出了正确的宽度,navbar中的{{windowWidth}
也输出了正确的宽度,甚至添加和删除类都可以工作!只是在windowWidth=1024
之前,更改的类似乎没有任何效果,我不知道为什么
有什么帮助吗
干杯:)您从未在挂载后设置
此窗口宽度
只需添加以下内容:
onResize(){
this.windowWidth=window.innerWidth//添加此行
...
}
我还想指出,如果不使用任何vue-/js magic,您想要实现的(移动和桌面上不同的导航栏样式)是非常可行的
如果您仍希望使用vue,则应使用vue方式:
这样做一个计算方法:
computed: {
isMobile() {
return this.windowWidth <= 768
}
}
计算:{
isMobile(){
返回此值。windowWidth