This tutorial is designed to teach you the ins and outs of route configuration in a Nuxt.js project. By the end of this guide, you will have a solid understanding of how Nuxt.js automatically generates routing configuration from your Vue files.
You will learn:
Prerequisites:
Nuxt.js automatically generates a Vue Router configuration based on your file tree of Vue files inside the pages
directory.
Let's create a simple pages
directory structure:
pages/
--| about.vue
--| index.vue
<template>
<h1>About Page</h1>
</template>
<template>
<h1>Home Page</h1>
</template>
This will automatically generate the following router configuration:
{
router: {
routes: [
{
name: 'index',
path: '/',
component: 'pages/index.vue'
},
{
name: 'about',
path: '/about',
component: 'pages/about.vue'
}
]
}
}
This means that if you navigate to /
, you will see the Home Page, and if you navigate to /about
, you will see the About Page.
If you want to create a dynamic route with a parameter, you can do so by adding an underscore before the .vue file or directory.
For example, if you want to create a route like /users/:id
, you can create a users
directory and an _id.vue
file inside it.
pages/
--| users/
-----| _id.vue
And in _id.vue
:
<template>
<h1>User ID: {{ $route.params.id }}</h1>
</template>
Now, if you navigate to /users/1
, you will see "User ID: 1".
To create nested routes, create a Vue file with the same name as the directory, and then create an index.vue
file inside that directory.
pages/
--| users/
-----| index.vue
-----| _id.vue
And in users/index.vue
:
<template>
<h1>Users Page</h1>
</template>
Now, if you navigate to /users
, you will see the Users Page.
In this tutorial, we've learned how Nuxt.js automatically generates routes based on the pages
directory. We've also learned how to create dynamic and nested routes.
For further learning, I recommend checking out the Nuxt.js routing documentation.
/products/:id
and display the product id.Solution: Create a products
directory and an _id.vue
file inside it. In _id.vue
, display the product id with {{ $route.params.id }}
.
/users/:id/posts
and display the user id and a "Posts" heading.Solution: Create a users
directory with an _id
directory inside it. Inside _id
, create a posts.vue
file. In posts.vue
, display the user id with {{ $route.params.id }}
and a "Posts" heading.
/users/:id/posts/:postId
and display the user id and the post id.Solution: Inside the users/_id/
directory, create a posts
directory with an _postId.vue
file inside it. In _postId.vue
, display the user id with {{ $route.params.id }}
and the post id with {{ $route.params.postId }}
.
Remember, practice makes perfect! Keep experimenting with different routes and configurations to master routing in Nuxt.js.