【问题标题】:Vue acting weird with condition relating to window widthVue 在与窗口宽度相关的条件下表现得很奇怪
【发布时间】:2020-07-23 12:06:42
【问题描述】:

所以我只是想让我的基本 Vue 导航栏功能正常工作,例如在滚动时更改类(效果很好)和在调整大小时更改类,我遇到了更多麻烦。

这是我<template>标签的内容:

  <nav class="navbar is-fixed-top navbar-max">
    {{windowWidth}}
  </nav> 

...以及我的&lt;script&gt;标签的相关内容:

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 之前似乎没有任何效果,我不知道为什么......

有什么帮助吗?

干杯:)

【问题讨论】:

    标签: javascript css vue.js


    【解决方案1】:

    你永远不会在挂载后设置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直接在导航标签上更新类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-03
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多