useRouter() | Vue Router
useRouter() is a composition API function that provides access to the router instance within your Vue components. This function enables programmatic navigation and access to router methods and properties. 🧭
📋 Function Signature
typescript
function useRouter(): Router🎯 Purpose and Functionality
The useRouter() function is the primary way to interact with the router instance in composition API components. It returns the router instance that was installed in the Vue application.
Key Use Cases:
- ✅ Programmatic Navigation - Navigate to different routes programmatically
- ✅ Router State Access - Access router configuration and state
- ✅ Navigation Control - Control navigation flow and behavior
- ✅ Route Information - Get information about current and previous routes
📤 Return Value
Returns the current Router instance that was installed in the Vue application.
💡 Basic Usage Examples
Simple Navigation
vue
<template>
<button @click="goToAbout">Go to About Page</button>
</template>
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
const goToAbout = () => {
router.push('/about')
}
</script>Navigation with Parameters
vue
<template>
<button @click="viewUser(123)">View User 123</button>
</template>
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
const viewUser = (userId) => {
router.push(`/user/${userId}`)
}
</script>🔧 Advanced Usage Patterns
Named Route Navigation
vue
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
// Navigate using named routes
const goToUserProfile = (userId) => {
router.push({
name: 'user-profile',
params: { id: userId }
})
}
// With query parameters
const searchUsers = (query) => {
router.push({
name: 'user-search',
query: { q: query }
})
}
</script>Navigation with State
vue
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
const navigateWithState = () => {
router.push({
path: '/checkout',
state: {
from: 'product-page',
productId: 456
}
})
}
</script>Navigation Guards Integration
vue
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
const protectedNavigation = async () => {
try {
await router.push('/admin')
// Navigation completed successfully
console.log('Navigation to admin completed')
} catch (error) {
// Navigation was prevented by a guard
console.error('Navigation blocked:', error)
showAccessDeniedMessage()
}
}
</script>🚨 Important Considerations
Component Context Requirement
vue
<script setup>
// useRouter() must be called within a component that has access to the router
// This typically means the component is a child of the app that uses the router
const router = useRouter() // ✅ Works in router-enabled components
// Outside of component context, you might need to import the router directly
// import router from './router'
</script>Navigation Timing
vue
<script setup>
import { useRouter, onMounted } from 'vue-router'
const router = useRouter()
onMounted(() => {
// Safe to navigate after component is mounted
if (someCondition) {
router.push('/redirect-target')
}
})
// Avoid navigating during setup as the router might not be ready
// router.push('/early-navigation') // ❌ Risky
</script>🔗 Related APIs
useRoute()- Access current route informationRouter- Router instance interface- Navigation Methods -
push(),replace(),go(),back(),forward()
📚 Navigation Methods
push() - Navigate to New Location
javascript
const router = useRouter()
// Various push method signatures
router.push('/path') // String path
router.push({ path: '/path' }) // Location object
router.push({ name: 'route-name' }) // Named route
router.push({ path: '/path', query: { id: 1 } }) // With queryreplace() - Replace Current Location
javascript
const router = useRouter()
// Replace current entry instead of adding to history
router.replace('/new-location')
router.replace({ name: 'home' })History Navigation Methods
javascript
const router = useRouter()
router.back() // Go back one step in history
router.forward() // Go forward one step in history
router.go(1) // Go forward 1 step
router.go(-2) // Go back 2 steps💡 Practical Examples
Form Submission Navigation
vue
<template>
<form @submit.prevent="handleSubmit">
<input v-model="formData.email" />
<button type="submit">Submit</button>
</form>
</template>
<script setup>
import { useRouter } from 'vue-router'
import { ref } from 'vue'
const router = useRouter()
const formData = ref({ email: '' })
const handleSubmit = async () => {
try {
// Submit form data
await submitForm(formData.value)
// Navigate to success page
router.push('/success')
} catch (error) {
// Navigate to error page
router.push('/error')
}
}
</script>Conditional Navigation
vue
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
const navigateIfAllowed = (targetPath) => {
if (userHasPermission(targetPath)) {
router.push(targetPath)
} else {
showPermissionError()
}
}
const handleLogout = () => {
// Clear authentication
clearAuth()
// Redirect to login
router.replace('/login')
}
</script>Navigation with Loading State
vue
<template>
<button @click="navigateWithLoading" :disabled="isNavigating">
{{ isNavigating ? 'Navigating...' : 'Go to Page' }}
</button>
</template>
<script setup>
import { useRouter } from 'vue-router'
import { ref } from 'vue'
const router = useRouter()
const isNavigating = ref(false)
const navigateWithLoading = async () => {
isNavigating.value = true
try {
await router.push('/target-page')
} finally {
isNavigating.value = false
}
}
</script>💡 Pro Tip: Always use
awaitwith navigation methods when you need to handle navigation completion or errors, especially when dealing with navigation guards.