Skip to main content

How do you declare a dynamic route?

A dynamic route is a route where part of the path is a variable (a parameter). It lets you create pages like:

/users/10 /products/42 /posts/my-article

In Vue Router, a dynamic route is declared using a colon (:) before the parameter name.


Example of declaring a dynamic route

js
const routes = [ { path: '/users/:id', component: UserPage } ]

Now the path /users/5 or /users/1234, both match this route.


How do you get the route parameter?

In the Composition API:

js
import { useRoute } from 'vue-router' const route = useRoute() console.log(route.params.id)

In the Options API:

js
this.$route.params.id

Example of usage with a component

router.js

js
const routes = [ { path: '/product/:productId', name: 'product', component: ProductPage } ]

ProductPage.vue

vue
<script setup> import { useRoute } from 'vue-router' const route = useRoute() console.log(route.params.productId) </script>

You can add several parameters

js
{ path: '/users/:userId/posts/:postId', component: PostPage }

Parameters can be made optional

js
{ path: '/search/:query?', component: SearchPage }

You can use regular expressions

js
{ path: '/user/:id(\\d+)', component: UserPage }

This allows only numeric ids.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.