Nuxt.js provides a powerful layout system that allows developers to create reusable layout components for applications, improving code reusability and consistency.
How the layout system works:
-
Default layout
- Nuxt.js uses
layouts/default.vueas the main layout for the application by default - All page components use this layout by default unless another layout is specified
- Nuxt.js uses
-
Layout file structure
- Layout files are stored in the
layoutsdirectory - Each layout file is a Vue component that must contain the
<nuxt />component to display page content
- Layout files are stored in the
-
Layout usage
- Specify the layout to use in page components via the
layoutproperty - Layout components wrap page components, providing a consistent page structure
- Specify the layout to use in page components via the
Creating and using custom layouts:
-
Creating layout files
- Create new layout files in the
layoutsdirectory, such aslayouts/auth.vue - Layout files must contain the
<nuxt />component to display page content
- Create new layout files in the
-
Basic layout structure
vue<!-- layouts/auth.vue --> <template> <div class="auth-layout"> <header>Authentication Page</header> <main> <nuxt /> </main> </div> </template>
- Using layouts in pages
vue<!-- pages/login.vue --> <template> <div>Login page content</div> </template> <script> export default { layout: 'auth' // Specify using auth layout } </script>
-
Layout lifecycle
- Layout components have full Vue lifecycle hooks
- The layout component's
fetchmethod executes before the page'sfetchmethod - Layout components can access the
$routeobject and adjust layout based on route changes
-
Dynamic layouts
- Can dynamically select layouts based on conditions
- For example, display different layouts based on user permissions
Advanced layout usage:
-
Nested layouts
- Can use other components in layouts to implement complex layout structures
- Can achieve nested layouts through the component's
layoutproperty
-
Layout transition effects
- Can add transition animations to layouts to improve user experience
- Wrap
<nuxt />with Vue's<transition>component
-
Layout middleware
- Can add middleware to layouts to handle logic such as permission validation
-
Layout data passing
- Can pass data between layouts and pages through
propsor$store
- Can pass data between layouts and pages through
Best practices:
- Create specialized layouts for different types of pages (e.g., authentication pages, admin backend, frontend pages)
- Use layout components appropriately to reduce code duplication
- Keep layout structures simple and avoid excessive nesting
- Use layout lifecycle hooks to handle global logic
- Add appropriate transition effects to layouts to improve user experience
Notes:
- Layout files must contain the
<nuxt />component, otherwise page content will not display - Layout component names should match file names (excluding .vue extension)
- The layout's
asyncDatamethod will not be called, usefetchmethod to get data