Layouts directory

Layouts are a great help when you want to change the look and feel of your Nuxt app. Whether you want to include a sidebar or have distinct layouts for mobile and desktop.


Layouts directory - 图1

This directory cannot be renamed without extra configuration.

Default Layout

You can extend the main layout by adding a layouts/default.vue file. It will be used for all pages that don’t have a layout specified. Make sure to add the <Nuxt> component when creating a layout to actually include the page component.

All you need in your layout is three lines of code which will render the page component.

layouts/default.vue

  1. <template>
  2. <Nuxt />
  3. </template>

You can add more components here such as Navigation, Header, Footer etc.

layouts/default.vue

  1. <template>
  2. <div>
  3. <TheHeader />
  4. <Nuxt />
  5. <TheFooter />
  6. </div>
  7. </template>

Layouts directory - 图2

If you have components set to true then there is no need to add any import statements for your components.

Custom Layout

Every file (top-level) in the layouts directory will create a custom layout accessible with the layout property in the page components.

Let’s say we want to create a blog layout and save it to layouts/blog.vue:

layouts/blog.vue

  1. <template>
  2. <div>
  3. <div>My blog navigation bar here</div>
  4. <Nuxt />
  5. </div>
  6. </template>

Then you have to tell the pages to use your custom layout

pages/posts.vue

  1. <script>
  2. export default {
  3. layout: 'blog',
  4. // OR
  5. layout (context) {
  6. return 'blog'
  7. }
  8. }
  9. </script>

Error Page

The error page is a page component which is always displayed when an error occurs (that is not thrown on the server-side).

Layouts directory - 图3

Though this file is placed in the layouts folder, it should be treated as a page.

As mentioned above, this layout is special and you should not include <Nuxt> inside its template. You must see this layout as a component displayed when an error occurs (404, 500, etc.). Similar to other page components, you can set a custom layout for the error page as well in the usual way.

You can customize the error page by adding a layouts/error.vue file:

layouts/error.vue

  1. <template>
  2. <div class="container">
  3. <h1 v-if="error.statusCode === 404">Page not found</h1>
  4. <h1 v-else>An error occurred</h1>
  5. <NuxtLink to="/">Home page</NuxtLink>
  6. </div>
  7. </template>
  8. <script>
  9. export default {
  10. props: ['error'],
  11. layout: 'blog' // you can set a custom layout for the error page
  12. }
  13. </script>

Layouts directory - 图4

The default error page source code is available on GitHub.