Routing in Nuxt

1/3/2025

Routing in Nuxt

Nuxt automatically creates routes based on the file structure inside the pages/ directory.

Basic Routes

Create files in the pages/ directory:

pages/
├── index.vue      # /
├── about.vue      # /about
└── contact.vue    # /contact

Dynamic Routes

Use square brackets to define dynamic segments:

pages/
├── users/
│   ├── index.vue        # /users
│   └── [id].vue         # /users/:id
└── posts/
    └── [slug].vue       # /posts/:slug

Accessing Route Parameters

vue
<script setup>
const route = useRoute()
const id = route.params.id
</script>

Use NuxtLink for navigation:

vue
<template>
  <NuxtLink to="/about">About</NuxtLink>
  <NuxtLink :to="{ name: 'users-id', params: { id: 1 } }">
    User 1
  </NuxtLink>
</template>

Programmatic Navigation

vue
<script setup>
const router = useRouter()

function goToUser(id) {
  router.push(`/users/${id}`)
}
</script>