DEV Community

Mattia Zanella
Mattia Zanella

Posted on • Edited on

8

Nuxt.js - Dynamic layouts by current route.

UPDATE 07/2020

I've updated the snippets below since in specific edge-cases when refreshing the page the middleware didn't work.

Given Nuxt documentation it seems like that it is not so easy for us to have different layouts by dynamic routes.

So I surfed the web and I've found a similar issue and, by the end of the day, this is my solution.

This is my structure:

pages/
   _page.vue
   index.vue
Enter fullscreen mode Exit fullscreen mode

The solution, already mentioned in the issue, is to create a middleware under middleware folder like this one:

/** 
 * @description myMiddleware.js
 * @see https://glitch.com/edit/#!/nuxt-dynamic-layouts?path=middleware/mobile.js:5:1
 */
export default context => {
  const { route: { params } } = context

  switch (params.page) {
    case 'tmp1':
    case 'tmp2':
        return 'tmpLayout'

      default:
        return 'default'
  }
}
Enter fullscreen mode Exit fullscreen mode

And inside _page.vue simply use this line:

  import myMiddleware from '@/middleware/myMiddleware'
  ...
  layout: myMiddleware,
Enter fullscreen mode Exit fullscreen mode

So whenever you navigate through mysite.com/tmp1 or mysite.com/tmp2 our tmpLayout will always used.

UPDATE 07/2020

I've updated the snippets above since in specific edge-cases when refreshing the page the middleware didn't work.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay