Computed property reactive to window.innerwidth in VueJS

匆匆过客 提交于 2021-02-18 20:29:54

问题


Basically, what I need is a computed property that returns true when the window.innerwidth is equal or lower than 768px and false when it's higher than 768px.

What I did:

computed: {
  isMobile() {
    if (window.innerWidth <= 768) {
      return true
    } 
    return false
  }
}

But that computes that property only once, and if I resize the window later, it doesn't react to that change. What can I do?


回答1:


Add an eventlistener to the window like so:

new Vue({
  el: "#app",
  data() { return { windowWidth: window.innerWidth } },
  mounted() {
    window.addEventListener('resize', () => {
      this.windowWidth = window.innerWidth
      console.log(this.isMobile)
    })
  },
  computed: {
    isMobile() {
      return this.windowWidth <= 768
    }
  }
})



回答2:


Computed properties are only updated when their depedencies change, therefore here isMobile won't be reactive.



来源:https://stackoverflow.com/questions/50490561/computed-property-reactive-to-window-innerwidth-in-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!