Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Layouts

A layout is a wrapper component with the repeating parts of a site: the header, the menu, the footer. A page is shown inside its layout, so you do not copy the header into every file. Layouts live in the app/layouts/ folder.

The default layout

Create a layout with a command:

npx nuxi add layout default

The file app/layouts/default.vue appears. Move the header from app.vue into it:

<!-- app/layouts/default.vue -->
<template>
  <div>
    <header>
      <nav>
        <NuxtLink to="/">Home</NuxtLink>
        <NuxtLink to="/posts">Posts</NuxtLink>
        <NuxtLink to="/about">About</NuxtLink>
      </nav>
    </header>
    <main>
      <slot />
    </main>
    <footer>Anna and Oleg's blog</footer>
  </div>
</template>

The current page goes in place of <slot />. A layout named default applies to every page that has not chosen another one.

Connecting it in app.vue

Layouts only work if app.vue wraps pages in <NuxtLayout>:

<!-- app/app.vue -->
<template>
  <div>
    <NuxtRouteAnnouncer />
    <NuxtLayout>
      <NuxtPage />
    </NuxtLayout>
  </div>
</template>

Open any page: the menu is on top, the footer at the bottom, and the page content in between.

A second layout

The blog admin area needs a different wrapper, without a footer and with another menu. Create app/layouts/admin.vue:

<!-- app/layouts/admin.vue -->
<template>
  <div class="admin">
    <header>
      <strong>Blog admin</strong>
      <NuxtLink to="/">Back to site</NuxtLink>
    </header>
    <slot />
  </div>
</template>

A layout is not used anywhere by itself: a page has to choose it.

Choosing a layout on a page

A page picks its layout with the definePageMeta function. Create app/pages/admin.vue:

<!-- app/pages/admin.vue -->
<script setup lang="ts">
definePageMeta({
  layout: 'admin'
})
</script>
 
<template>
  <section>
    <h2>Dashboard</h2>
  </section>
</template>

At /admin the admin layout is used, and the other pages get default. The value layout: false turns the layout off completely.

What definePageMeta does

definePageMeta describes page settings that Nuxt reads already at build time. Besides the layout, it lists checks that run before entering the page; the middleware lesson covers them. You cannot use component variables inside it, only ready values.

Common mistake

The file app/layouts/default.vue exists, yet the header does not appear. The cause is almost always app.vue: it has no <NuxtLayout>, so Nuxt shows the page without a wrapper. Check that <NuxtPage /> sits inside <NuxtLayout>, and remove the old header from app.vue so it is not shown twice.

Thanks for reading!

Donate to the site — we work hard for you.