[Vuejs]-Set variable to true or false depending of screen width in vue js

0๐Ÿ‘

โœ…

If you do this then the variable will update when the screen width changes and will not continually fire like a resize event will.

<script setup>
const isMobile = ref('')
let mql

function handleMqlChange(e) {
  isMobile.value = e.matches
}

onMounted(() => {
  mql = window.matchMedia('(max-width: 1024px)')
  isMobile.value = mql.matches
  mql.addEventListener('change', handleMqlChange)
})

onUnmounted(() => {
  mql.removeEventListener('change', handleMqlChange)
})
</script>

You can then use a simple v-if="isMobile". This will work when the page loads and also when the user changes the screen size, whether that be an orientation change on a mobile device or a browser tab resize.

0๐Ÿ‘

The global window variable has all the information you need regarding screen width. Here is an example of what window.screen gives you.

Screen {
  availHeight
  availLeft
  availTop
  availWidth
  colorDepth
  height
  isExtended
  onchange
  orientation: ScreenOrientation {
    angle
    onchange
    type
    [[Prototype]]: ScreenOrientation
  }
  pixelDepth
  width
  [[Prototype]]: Screen
}

Simply define reactive property to window.screen.width or window.screen.availWidth depending on your use case.

Leave a comment