Learn Nuxt Β· 2/12

File-Based Routing: Navigating the App

5 min read

Navigating Your Nuxt App: A Guide to File-Based Routing πŸ—ΊοΈ

Welcome, intrepid coder, to the wonderful world of Nuxt routing! Forget deciphering complex routing configuration files. Nuxt offers a more intuitive and streamlined approach: file-based routing. This means the way you structure your files and folders directly dictates your application's routes. It's like having a self-organizing map for your web app!

The Problem: In many web frameworks, defining the different pages (or routes) of your application requires manually creating a list of paths and connecting them to their corresponding components. This can become cumbersome and error-prone as your application grows. Imagine having to manually update a giant spreadsheet every time you add a new page – not fun.

The Solution: Nuxt's file-based routing automates this process. By simply creating .vue files within a special pages directory, Nuxt automatically generates the corresponding routes. This keeps your project organized and your routing logic crystal clear.


1. The pages Directory: Your App's Roadmap πŸ“‚

At the heart of Nuxt's routing is the pages directory. Think of it as the blueprint for your application's navigation. Every .vue file you create inside this directory becomes a route.

Let's Get Practical:

  1. Create a pages directory in the root of your Nuxt project if it doesn't already exist.
  2. Inside the pages directory, create two files: index.vue and about.vue.
1c
-| pages/
---| index.vue
---| about.vue

What just happened? You've effortlessly created two routes:

  • pages/index.vue maps to the root of your site (/).
  • pages/about.vue maps to /about.

pages/index.vue

vue
<template>
  <h1>Welcome to the Homepage! 🏠</h1>
</template>

pages/about.vue

vue
<template>
  <h1>About Us πŸ§‘β€πŸš€</h1>
</template>

It's that simple! Nuxt scans this directory and wires everything up for you. No manual router configuration needed.


2. Dynamic Routes: Handling IDs and Parameters πŸ†”

Static pages are great, but what about when you need to display information based on a specific ID or slug, like a blog post or a user profile? This is where dynamic routes come in.

The Problem: You don't want to create a separate .vue file for every single blog post or user. That would be a maintenance nightmare!

The Solution: Nuxt allows you to create dynamic routes by prefixing a .vue file or a directory with an underscore (_) in Nuxt 2, or by wrapping the parameter in square brackets ([]) in Nuxt 3 and later versions. This tells Nuxt that this part of the URL is a variable.

Let's build a blog:

Create a file structure like this:

1c
-| pages/
---| blog/
-----| [slug].vue

Now, you can access URLs like /blog/my-first-post or /blog/learning-nuxt. The slug part of the URL is now available as a parameter in your component.

pages/blog/[slug].vue

vue
<template>
  <h1>{{ $route.params.slug }}</h1>
</template>

<script setup>
const route = useRoute()
console.log(route.params.slug)
</script>

In this example, $route.params.slug will contain the value from the URL. So, if you navigate to /blog/hello-world, the heading will display "hello-world".

Fun Fact: This convention of using brackets for dynamic segments is becoming a standard in modern web frameworks, making it easier for developers to switch between them.


3. Nested Routes: Parent and Child Views πŸ‘¨β€πŸ‘©β€πŸ‘§

Sometimes, you need to render a view inside another view. For example, a user dashboard might have sub-sections for profile, settings, and billing, all within the main dashboard layout.

The Problem: How do you structure your routes so that some parts of the page remain the same while others change based on the URL?

The Solution: Nuxt handles nested routes by creating a directory and a .vue file with the same name. The .vue file acts as the parent layout for the child routes defined within the directory.

Let's create a dashboard:

  1. Create a dashboard.vue file in your pages directory.
  2. Create a dashboard directory in your pages directory.
  3. Inside the dashboard directory, create profile.vue and settings.vue.
1c
-| pages/
---| dashboard/
-----| profile.vue
-----| settings.vue
---| dashboard.vue

Now, you have the following routes:

  • /dashboard/profile
  • /dashboard/settings

To tell Nuxt where to render the child components (profile.vue and settings.vue), you need to add the <NuxtPage /> component inside dashboard.vue.

pages/dashboard.vue

vue
<template>
  <div>
    <h2>Dashboard</h2>
    <nav>
      <NuxtLink to="/dashboard/profile">Profile</NuxtLink>
      <NuxtLink to="/dashboard/settings">Settings</NuxtLink>
    </nav>
    <hr>
    <NuxtPage /> 
  </div>
</template>

pages/dashboard/profile.vue

vue
<template>
  <h3>User Profile</h3>
</template>

pages/dashboard/settings.vue

vue
<template>
  <h3>Account Settings</h3>
</template>

Now, when you navigate to /dashboard/profile or /dashboard/settings, the content of profile.vue or settings.vue will be rendered where you placed <NuxtPage /> inside dashboard.vue.


4. NuxtLink: Seamless Client-Side Navigation πŸš€

To navigate between the pages you've created, you might be tempted to use the standard <a> tag. However, this would cause a full-page reload every time a user clicks a link, which can feel slow and clunky.

The Problem: Full-page reloads are inefficient and lead to a poor user experience in a single-page application (SPA).

The Solution: Nuxt provides the <NuxtLink> component, which is a wrapper around Vue Router's <router-link>. It enables smooth, client-side transitions between pages without a full refresh.

How to use it:

Simply replace your <a> tags with <NuxtLink> and the href attribute with to.

vue
<template>
  <nav>
    <NuxtLink to="/">Home</NuxtLink>
    <NuxtLink to="/about">About</NuxtLink>
    <NuxtLink to="/blog/my-first-post">My First Post</NuxtLink>
  </nav>
</template>

A Cool Feature - Smart Prefetching: One of the superpowers of <NuxtLink> is its ability to intelligently prefetch the code for linked pages when they become visible in the viewport. This means that by the time the user clicks the link, the next page is likely already loaded, resulting in near-instant navigation. This happens automatically when the browser is idle, and it's smart enough not to prefetch on slow connections.


Further Reading & References πŸ“š

Challenge

You are building a multi-section web application using Nuxt.js. Your task is to define the file structure within the pages directory and write the corresponding Vue component code to establish a specific routing configuration.

Requirements:

  1. Create a file structure that generates the following routes:

    • A homepage at the root URL (/).
    • A blog listing page at /blog.
    • A dynamic route for individual blog posts that captures a post's unique identifier, e.g., /blog/a-post-slug.
    • A nested route structure for a user dashboard at /dashboard.
    • Two child routes under the dashboard: one for user profile at /dashboard/profile and another for account settings at /dashboard/settings.
  2. Implement the following component logic:

    • The blog listing page (/blog) must include a <NuxtLink> that navigates to a sample post at /blog/my-first-post.
    • The dynamic blog post page must access and display the post's slug from the URL parameters.
    • The main dashboard component (/dashboard) must act as a layout and include the necessary component to render its child routes.

Expected result

Your submission should be a single code block containing the file structure and component code. The file paths must be specified in comments directly above their corresponding Vue component code.

The correct solution must define the following file structure and content:

  • pages/index.vue: Contains a simple template for the homepage, like <h1>Homepage</h1>.
  • pages/blog.vue: Contains a template with a <NuxtLink to="/blog/my-first-post">My First Post</NuxtLink>.
  • pages/blog/[slug].vue: This file creates the dynamic route. Its template must display the route parameter, for example: <h1>Blog Post: {{ $route.params.slug }}</h1>. It should also include a <script setup> block that properly accesses the route, for instance, by using const route = useRoute();.
  • pages/dashboard.vue: This file serves as the parent layout for the nested dashboard routes. Its template must contain the <NuxtPage /> component to render child pages.
  • pages/dashboard/profile.vue: A simple component for the user profile, e.g., <h3>User Profile</h3>.
  • pages/dashboard/settings.vue: A simple component for account settings, e.g., <h3>Account Settings</h3>.

The file paths, including the directory structure and the use of square brackets [...] for the dynamic route, must be exact.

vue

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.