loading...

Nuxt.js - Dynamic layouts by current route.

alligatore3 profile image Mattia Zanella ・1 min read

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

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

// 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':
        context.dynamicLayout = 'tmpLayout'
        break;

      default:
        context.dynamicLayout = 'default'
        break;
  }
}

And inside _page.vue simply use this line:

  layout: ({ dynamicLayout }) => dynamicLayout,

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

Posted on Apr 14 by:

alligatore3 profile

Mattia Zanella

@alligatore3

Trying to deal with @vuejs at L.I.F.E. ITALIA S.R.L.

Discussion

markdown guide