#Dynamic routes examples
3 messages · Page 1 of 1 (latest)
Hi @clever rampart. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Certainly! I'd be happy to provide you with examples of dynamic routes in Nuxt. Dynamic routes are a powerful feature that allows you to create flexible and reusable page components.
Here's a sample of how to use dynamic routes in Nuxt:
- Create a file with square brackets in its name to define a dynamic segment:
pages/
--| users/
-----| [id].vue
In this example, [id] is the dynamic part of the route.
- In your
[id].vuefile, you can access the dynamic parameter using theuseRoute()composable:
<script setup>
const route = useRoute()
const userId = route.params.id
</script>
<template>
<div>
<h1>User {{ userId }}</h1>
</div>
</template>
This setup will match routes like /users/1, /users/2, etc., and userId will contain the value of the dynamic segment.
For more complex scenarios, you can also use catch-all routes. Here's an example:
pages/
--| articles/
-----| [...slug].vue
This will match any route under /articles/, such as /articles/2023/best-practices.
You can access the parameters like this:
<script setup>
const route = useRoute()
console.log(route.params.slug) // ['2023', 'best-practices']
</script>
These examples are based on the information from Nuxt Documentation on Routing (https://nuxt.com/docs/getting-started/routing).