So i wanted to choose a different layout if the window width is less than 1000px or w/e for like a mobile friendly version.
i did this.
/middleware/mobile.js
export default function ({store}) {
let w
if (process.BROWSER_BUILD) {
w = window.innerWidth
}
if (w < 1111) {
store.commit('mobileOn')
} else {
store.commit('mobileOff')
}
}
mobileOn and mobileOff just set $store.state.mobile to either true or false.
then added this in the nuxt.config
router: {
middleware: ['mobile']
},
then put this in the page
export default {
layout ({store}) { return store.state.mobile ? 'mobile' : 'default' }
}
But i cant get it to work on the initial load, it would load up the default layout first. Works fine if i go to a new page though.
kinda just figuring stuff out as i go.
Hi @knifoon
The layout is first server-rendered, sadly there is not http header to give you the screen resolution on server-side.
You may want to check the http user-agent to know it the device is a mobile/tablet vs a computer to guess the screen resolution on the server side, see https://github.com/nuxt/nuxt.js/blob/dev/examples/dynamic-layouts/middleware/mobile.js
@knifoon very old issue I know. I have been thinking about this a lot lately and the best way seems to come from this thread: https://github.com/nuxt/nuxt.js/issues/1154. Create a plugin with
export default ({ app, store }, inject) => {
app.mounted = () => {
if (w < 1111) {
store.commit('mobileOn')
} else {
store.commit('mobileOff')
}
}
}
And then add this to plugins in nuxt.config with ssr set to false. This works on initial load and works the best of all the methods I have tried. Checking for user agents is the next best thing, but found it to be unreliable in some cases.
It is a nice workaround @ImreC but you have to make sure that no "flash" happens when updating the store state when changing the design to mobile.
@Atinux you are right. I must mention that my page is responsive. It is just to trigger certain components further down. In my mind it would still be utopia to be able to load components based on screen size, but guess that will just remain wishful thinking with current browsers..
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Most helpful comment
Hi @knifoon
The layout is first server-rendered, sadly there is not http header to give you the screen resolution on server-side.
You may want to check the http user-agent to know it the device is a mobile/tablet vs a computer to guess the screen resolution on the server side, see https://github.com/nuxt/nuxt.js/blob/dev/examples/dynamic-layouts/middleware/mobile.js