Working with Dynamic Routes in Nuxt.js

Tutorial 2 of 5

Introduction

In this tutorial, we'll learn how to work with dynamic routes in Nuxt.js, a robust framework for building Vue.js applications. Dynamic routes are routes that depend on server data or user input. They are especially useful when you want to create pages for individual items from a list, such as blog posts, products, or users.

At the end of this tutorial, you will be able to create and manage dynamic routes in your Nuxt.js application.

Prerequisites
You should have a basic understanding of Vue.js and Nuxt.js. Familiarity with JavaScript ES6 syntax and axios for HTTP requests is also beneficial.

Step-by-Step Guide

Understanding Dynamic Routes

In Nuxt.js, to define a dynamic route, you create a Vue file with an underscore (_) as the prefix. For example, _slug.vue or _id.vue.

Creating Dynamic Routes

  1. In your pages directory, create a new file with an underscore prefix. Let's say _id.vue.
  2. This file will be converted to a route with a dynamic segment like /users/:id.

Code Examples

Let's take a look at a practical example. We will create a dynamic route for blog posts.

  1. In the pages directory, create a new directory named posts. Inside posts, create a new file named _id.vue.
<template>
  <div>
    <h1>{{ post.title }}</h1>
    <p>{{ post.body }}</p>
  </div>
</template>

<script>
export default {
  async asyncData({ params }) {
    const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${params.id}`);
    const post = await res.json();
    return { post };
  }
}
</script>

In the above code:

  • We’re using the special asyncData method provided by Nuxt.js. This method is called before loading the component and fetches data based on the dynamic route parameter id.
  • The fetched post data is returned and merged with the component data.

You can navigate to this dynamic page by using the nuxt-link component:

<nuxt-link :to="`/posts/${post.id}`">{{ post.title }}</nuxt-link>

Summary

In this tutorial, we've learned how to create dynamic routes in Nuxt.js. We created a blog posts page where each post has its own URL based on its id.

Next steps for learning include exploring how to handle dynamic nested routes and validating route parameters.

Practice Exercises

  1. Create a dynamic route for displaying users. Fetch user data from https://jsonplaceholder.typicode.com/users/1.

  2. Create a dynamic nested route for displaying comments for specific posts. Fetch comments data from https://jsonplaceholder.typicode.com/comments?postId=1.

Remember to validate the data returned from the API requests and handle any errors.

Additional Resources