Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 630
Sebastian Jung Avatar asked Nov 15 '25 09:11

Sebastian Jung


1 Answers

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"

like image 114
Nick Dawes Avatar answered Nov 18 '25 05:11

Nick Dawes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!