nuxt layout - having distinct layouts for mobile and desktop

Viewed 1282
import { isMobile } from 'mobile-device-detect'

export default {
    layout(context) {
        const mobile = isMobile ? 'mobile-layout' : 'desktop-layout
        return mobile
    }
}

I am creating a nuxt app. i am trying to detect when the view is either mobile or desktop. if i make a change to the code in my ide and save then isMobile is true and and it will get set to mobile-layout. However once you refresh the page isMobile is false and it will get set to desktop-mobile.

Im assuming that the layout is being set before it has time to determine if isMobile is true or false and automatically being set too false.

I cant figure out how to make something like this work. No matter what i try it always fails.

1 Answers

Why go for some general package when we have official support for this purpose by Nuxt community only? I would recommend you to use @nuxtjs/device module.

What makes it special? This.

This module injects flags that indicate a device type into the context and the component instance.

And this is how you can change the Layout dynamically. It is mentioned in the package's documentation. https://github.com/nuxt-community/device-module#nuxtjsdevice

export default {
    layout: (ctx) => ctx.isMobile ? 'mobile' : 'default'
}
Related