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.
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
.
_id.vue
./users/:id
.Let's take a look at a practical example. We will create a dynamic route for blog posts.
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:
asyncData
method provided by Nuxt.js. This method is called before loading the component and fetches data based on the dynamic route parameter id
.You can navigate to this dynamic page by using the nuxt-link
component:
<nuxt-link :to="`/posts/${post.id}`">{{ post.title }}</nuxt-link>
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.
Create a dynamic route for displaying users. Fetch user data from https://jsonplaceholder.typicode.com/users/1
.
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.