Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computed property reactive to window.innerwidth in VueJS

Tags:

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?

like image 567
Carlos Pisarello Avatar asked May 23 '18 14:05

Carlos Pisarello


People also ask

Is computed property reactive in Vue?

The Basics of Vue Reactivity Simply put, a computed property's dependencies are the reactive values that help the property that determine the value that is returned. If none of these change, then, again, the cached value will be returned. If no reactive dependency is changed, a computed property is not recalculated.

What is the difference between watch and computed in Vuejs?

Computed props can react to changes in multiple props, whereas watched props can only watch one at a time. Computed props are cached, so they only recalculate when things change. Watched props are executed every time.


2 Answers

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
    }
  }
})
like image 193
Get Off My Lawn Avatar answered Sep 28 '22 02:09

Get Off My Lawn


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

like image 28
Oli Crt Avatar answered Sep 28 '22 02:09

Oli Crt