You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: content/2.concepts/3.routing/index.md
+52-1
Original file line number
Diff line number
Diff line change
@@ -4,4 +4,55 @@ ogImage: true
4
4
5
5
# Routing
6
6
7
-
[Back to index](/)
7
+
## File-based routing
8
+
9
+
The file-based routing is one of Nuxt’s core features.\
10
+
Each Vue file inside the `pages/` directory corresponds to a URL (route) and renders its content.\
11
+
For example, `pages/index.vue` corresponds to `/`, and `pages/foo.vue` corresponds to `/foo`.\
12
+
This routing system is built on [vue-router](https://router.vuejs.org/).
13
+
14
+
Additionally, Nuxt optimizes each page through code splitting and other techniques, ensuring that only the minimal JavaScript required for the requested route is delivered.
15
+
16
+
## Navigation
17
+
18
+
Once you've created routes inside the `pages/` directory, you can use the `<NuxtLink>` component for navigation.
19
+
20
+
The `<NuxtLink>` component allows you to specify the route using the `to` prop to create links.\
21
+
Compared to using an `<a>` tag with an `href` attribute, `<NuxtLink>` automatically optimizes navigation, resulting in faster page transitions.
22
+
23
+
## Route Parameters
24
+
25
+
Inside the `/pages` directory, you can define dynamic routes by wrapping part of the filename in `[]`.\
26
+
For example: `pages/posts/[id].vue`.
27
+
28
+
The route parameter inside `[]` can be accessed via `useRoute()`.
29
+
30
+
```vue
31
+
<!-- pages/posts/[id].vue -->
32
+
<script setup lang="ts">
33
+
const route = useRoute()
34
+
35
+
// When accessing /posts/1, route.params.id will be 1
36
+
console.log(route.params.id)
37
+
</script>
38
+
```
39
+
40
+
## Challenge
41
+
42
+
Try implementing the `/posts/[id]` route and enabling navigation from `/` and `/foo` to `/posts/[id]`.\
43
+
Additionally, in `/posts/[id]`, read the `id` from the route parameter and display it on the screen.
44
+
45
+
### Steps to complete:
46
+
47
+
1. In `pages/posts/[id].vue`, use `useRoute()` to get `id` from `params` and display it on the screen.
48
+
2. In `pages/index.vue` and `pages/foo.vue`, use `<NuxtLink>` to create links that navigate to `/posts/[id]`.\
49
+
For example, create a link that navigates to `/posts/1` (you can use any value).
50
+
51
+
If you get stuck, click the button below or the one in the top-right corner of the editor to view the solution.
The `useRoute` function and `<NuxtLink>` component introduced in this section are automatically imported by Nuxt’s Auto Imports feature, so you don’t need to manually import them.\
58
+
In the next section, we will explore [Auto Imports](/concepts/auto-imports) in more detail.
0 commit comments