How to Get Route Params in Vue: Simple Guide
In Vue, you get route parameters using
useRoute() from vue-router. Access the params with const route = useRoute() and then route.params.paramName inside your component.Syntax
To get route params in Vue, first import useRoute from vue-router. Then call useRoute() inside your setup function to get the current route object. Access params via route.params.
useRoute(): Hook to get current route info.route.params: Object holding all route parameters.paramName: The name of the parameter you want.
javascript
import { useRoute } from 'vue-router' export default { setup() { const route = useRoute() const id = route.params.id return { id } } }
Example
This example shows a Vue component that reads a route parameter called id and displays it. The route URL might look like /user/123, where 123 is the id param.
vue
<template>
<div>
<h2>User ID: {{ id }}</h2>
</div>
</template>
<script setup>
import { useRoute } from 'vue-router'
const route = useRoute()
const id = route.params.id
</script>Output
User ID: 123
Common Pitfalls
1. Trying to access route.params outside setup() or before the router is ready can cause errors.
2. Forgetting to define the route param in your router config means route.params will be empty.
3. Using this.$route.params only works in Options API, not in Composition API.
javascript
/* Wrong: Using this.$route in setup() */ export default { setup() { // this.$route is undefined here const id = this.$route.params.id return { id } } } /* Right: Use useRoute() hook */ import { useRoute } from 'vue-router' export default { setup() { const route = useRoute() const id = route.params.id return { id } } }
Quick Reference
| Concept | Usage | Notes |
|---|---|---|
| Import useRoute | import { useRoute } from 'vue-router' | Needed to access route info in Composition API |
| Get route object | const route = useRoute() | Call inside setup() |
| Access param | route.params.paramName | Replace paramName with your param key |
| Options API param | this.$route.params.paramName | Only in Options API, not recommended now |
| Define param | path: '/user/:id' | Router config must declare params |
Key Takeaways
Use the useRoute() hook inside setup() to access route params in Vue.
Access parameters with route.params.paramName matching your route definition.
Ensure your router path defines the param with a colon, like /user/:id.
Avoid using this.$route in Composition API; prefer useRoute().
Accessing params before router is ready or outside setup() causes errors.