Home > Enterprise >  How to properly render html conditionally based on screen size in conjunction with ssr in vue/nuxt
How to properly render html conditionally based on screen size in conjunction with ssr in vue/nuxt

Time:04-07

Let's say i have markup to be rendered only for desktop via v-if.

If it's mobile it should render something v-else.

I am using the package vue-mq which allows for setting a default breakpoint which should be used for server side rendering.

When i put 'sm' in there and load the page from a desktop the browser obviously first receives the 'sm' version of the site which might differ from the 'lg' version.

Therefore a mismatch is caused showing up in the console.

What's the right way of conditionally rendering html content for ssr in nuxt/vuejs?

Any ideas on how to properly solve this without having the user load both versions of markup (like when using v-show instead of v-if which solves the mismatch but does add to the bandwidth usage)?

Any help is very much appreciated.

Thanks!

CodePudding user response:

You want @nuxtjs/device. When a http request hits your Nuxt app, this module inspects the user agent header and determines if the user agent (that is, the device the request originated from) is a mobile, a tablet, a desktop etc. This happens server side, before your client side code executes, and so v-if’s in templates will be handled properly.

For example:

v-if="$device.isMobile"

  • Related