How to Use useRouter in Vue: Simple Guide with Examples
In Vue 3 with Vue Router, you use
useRouter inside setup() to get the router instance. This lets you navigate programmatically by calling methods like router.push() to change routes.Syntax
The useRouter function is imported from vue-router and called inside the setup() function of a Vue component. It returns the router instance, which you can use to navigate or access route info.
import { useRouter } from 'vue-router': imports the hook.const router = useRouter(): gets the router instance.router.push('/path'): navigates to a new route.
javascript
import { useRouter } from 'vue-router' export default { setup() { const router = useRouter() // Use router to navigate return { router } } }
Example
This example shows a button that, when clicked, uses useRouter to navigate to the '/about' page programmatically.
vue
<template> <button @click="goToAbout">Go to About</button> </template> <script setup> import { useRouter } from 'vue-router' const router = useRouter() function goToAbout() { router.push('/about') } </script>
Output
A button labeled 'Go to About' that navigates to the '/about' route when clicked.
Common Pitfalls
Common mistakes when using useRouter include:
- Calling
useRouteroutsidesetup()or outside a Vue component context, which causes errors. - Forgetting to import
useRouterfromvue-router. - Using
router.push()with incorrect path strings or objects. - Not handling navigation failures or promises returned by
router.push().
javascript
/* Wrong: useRouter called outside setup */ const router = useRouter() // ❌ This will cause an error /* Right: useRouter inside setup */ export default { setup() { const router = useRouter() // ✅ Correct usage return { router } } }
Quick Reference
| Method | Description |
|---|---|
| useRouter() | Returns the router instance inside setup() |
| router.push(path) | Navigate to a new route by path or name |
| router.replace(path) | Navigate without adding a new history entry |
| router.currentRoute | Access the current route object (readonly) |
Key Takeaways
Always call useRouter() inside the setup() function of a Vue component.
Use router.push('/path') to navigate programmatically to a new route.
Import useRouter from 'vue-router' before using it.
Handle navigation promises if you need to react to success or failure.
Avoid calling useRouter outside Vue component setup to prevent errors.