0
0
VueHow-ToBeginner · 3 min read

How to Use useRoute in Vue: Simple Guide with Examples

In Vue, you use the useRoute hook from vue-router to access the current route's information inside a setup function. It returns a reactive object with details like path, params, and query, letting you react to route changes easily.
📐

Syntax

The useRoute hook is imported from vue-router and called inside the setup() function of a Vue component. It returns a reactive route object containing properties like path, params, and query.

Example parts:

  • import { useRoute } from 'vue-router': imports the hook
  • const route = useRoute(): gets the current route object
  • route.params: access dynamic route parameters
  • route.query: access URL query parameters
javascript
import { useRoute } from 'vue-router'

export default {
  setup() {
    const route = useRoute()
    // route is reactive and updates on route change
    return { route }
  }
}
💻

Example

This example shows a Vue component that uses useRoute to display the current route's path and a dynamic parameter called id. When the route changes, the displayed info updates automatically.

vue
<template>
  <div>
    <h2>Current Path: {{ route.path }}</h2>
    <p>Parameter ID: {{ route.params.id }}</p>
  </div>
</template>

<script setup>
import { useRoute } from 'vue-router'

const route = useRoute()
</script>
Output
Current Path: /user/123 Parameter ID: 123
⚠️

Common Pitfalls

1. Using useRoute outside setup(): The hook only works inside the setup() function or other composition functions.

2. Not importing from vue-router: Forgetting to import useRoute causes errors.

3. Trying to destructure route directly: Since route is reactive, destructuring its properties breaks reactivity. Always access properties via route.property.

javascript
/* Wrong: destructuring breaks reactivity */
const { params } = useRoute()
console.log(params.id) // won't update on route change

/* Right: keep route reactive */
const route = useRoute()
console.log(route.params.id) // reactive and updates
📊

Quick Reference

PropertyDescription
route.pathCurrent full path as a string
route.paramsObject with dynamic route parameters
route.queryObject with URL query parameters
route.nameName of the current route
route.fullPathFull resolved URL including query and hash

Key Takeaways

Use useRoute inside the setup() function to access current route info.
Access route properties like path, params, and query via the reactive route object.
Do not destructure route properties directly to keep reactivity intact.
Always import useRoute from vue-router before using it.
The route object updates automatically when the route changes.