26

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?

0

3 Answers 3

42

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
    }
  }
})
5
  • i also setted the value of the variable on mounted apart of adding the eventListener, so at the start windowWidth is not zero and the computed returns an incorrect value. Commented May 23, 2018 at 14:43
  • 5
    As a rule, shouldn't you always remove eventlisteners in beforeDestroy()?
    – Sebastian
    Commented Feb 19, 2020 at 6:54
  • Getting 'window is undefined' when instantiated in the data like this. Commented Sep 29, 2021 at 12:16
  • You'll need to assign this.windowWidth = window.innerWidth inside of the mounted function (before the event listener) to avoid the 'window is undefined' error Commented Sep 29, 2021 at 13:08
  • I made exactly like this but in mixin and my isMobile computed prop doesn't updating( Commented Jun 29, 2022 at 13:16
3

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

3

An other possibily is to use Vuetify:

computed: {
  isMobile() {
    return this.$vuetify.breakpoint.smAndDown
  },
},

src: https://vuetifyjs.com/en/features/breakpoints/#breakpoint-service-object

1
  • I was already using Vuetify but didn't know this was a feature. Nice tip!
    – groksrc
    Commented Aug 27, 2022 at 12:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.