0

I am working on a NuxtJS project. For getting the current screen width in real-time, I created an instance variable based on Accessing screen width in vue components and “window is not defined” in Nuxt.js.

But, the value is not getting updated in real-time. Either there is a delay or I need to refresh. I just need only the current screen width if it is less than 500px it should be true or false.

plugins/breakpoints.js

import Vue from 'vue'

Vue.prototype.$isMobile = Vue.observable(window.innerWidth < 600)

window.addEventListener(
  'resize',
  () => (Vue.prototype.$isMobile = window.innerWidth < 600)
)

nuxt.config.js

plugins: [{ src: './plugins/breakpoints', ssr: false }],

pages/index.vue

<template>
  <section>
    <h1>isMobile {{ $isMobile }}</h1>
  </section>
</template>

<script>
export default {
  name: 'IndexPage',
}
</script>

CodeSandBox(for quick preview): https://codesandbox.io/p/sandbox/reverent-stitch-1sdh6r

kissu
  • 40,416
  • 14
  • 65
  • 133
  • You're using [this module](https://github.com/nuxt-community/device-module) here? Also, what is the end goal in your case? Can't you achieve the same result with bare CSS? `ssr: false` should be `mode: 'client'` btw. – kissu Dec 27 '22 at 16:45
  • Not using `device-module` (don't know if it is built-in). My end goal is there are some pages where I am conditionally rendering based on the isMobile property. If it is related to CSS only, yea I know we can use @media query, and when applying `mode: 'client'` is not working either – Jim Parsons Dec 27 '22 at 16:55

0 Answers0