#Dynamic routes examples

3 messages · Page 1 of 1 (latest)

clever rampart
#

Can I get a sample when using a dynamic route?

silent horizonBOT
#

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:

  1. 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.

  1. In your [id].vue file, you can access the dynamic parameter using the useRoute() 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).

Remember that Nuxt automatically generates the router configuration based on your file structure in the pages/ directory, making it easy to create dynamic routes without additional configuration.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: