Welcome to Part 3 of our Nuxt.js tutorial series! In this segment, we'll delve into layouts and routing in Nuxt.js. Layouts provide a consistent structure for your application, while routing determines how users navigate between different pages.
Layouts in Nuxt.js
Layouts in Nuxt.js are Vue components that wrap your page components, providing a common structure across multiple pages. They are stored in the layouts
directory and can include headers, footers, sidebars, and other elements shared across your application.
Creating Layouts
To create a layout, simply define a .vue
file in the layouts
directory.
<!-- layouts/default.vue -->
<template>
<div>
<header>
<!-- Header content here -->
</header>
<main>
<nuxt />
</main>
<footer>
<!-- Footer content here -->
</footer>
</div>
</template>
In the above example, the <nuxt />
component is a placeholder that will be replaced with the content of the page being rendered.
Using Layouts
To use a layout, specify it in the front matter of your page components or use it as the default layout for all pages.
<!-- pages/index.vue -->
<template>
<div>
<h1>Home Page</h1>
<p>Welcome to my website!</p>
</div>
</template>
<script>
export default {
layout: 'default'
};
</script>
Routing and Nested Routes
Nuxt.js supports nested routes, allowing you to create complex page structures with ease.
Nested Routes
To create nested routes, create a directory with the same name as your parent route and add child page components inside it.
pages/
--| products/
-----| index.vue
-----| _id.vue
In this example, accessing /products
will render pages/products/index.vue
, while accessing /products/:id
will render pages/products/_id.vue
.
Conclusion
In this part of the tutorial series, we explored layouts and routing in Nuxt.js. Layouts provide a consistent structure for your application, while routing determines how users navigate between different pages. We also learned about nested routes, which allow for more complex page structures.
In Part 4, we'll dive deeper into data fetching in Nuxt.js, exploring different strategies for fetching data in your applications. Stay tuned!
If you have any questions or need further clarification, feel free to ask. Happy coding!