How to navigate programmatically in Vue Router
Programmatic navigation in Vue Router enables dynamic route changes triggered by user actions, form submissions, or application logic beyond simple link clicks. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented programmatic navigation in complex user flows, authentication systems, and conditional routing scenarios. From my expertise, the most versatile approach is using the router instance methods like push, replace, and go for different navigation behaviors. This pattern provides complete control over navigation timing, conditions, and user experience flow in Vue applications.
Use router instance methods like push, replace, and go to navigate programmatically based on application logic.
import { useRouter } from 'vue-router'
export default {
setup() {
const router = useRouter()
const navigateToUser = (userId) => {
router.push(`/user/${userId}`)
}
const navigateWithObject = () => {
router.push({
name: 'UserProfile',
params: { id: 123 },
query: { tab: 'settings' }
})
}
const replaceCurrentRoute = () => {
router.replace('/dashboard')
}
const goBackInHistory = () => {
router.go(-1)
}
const navigateAfterAction = async () => {
try {
await saveUserData()
router.push('/success')
} catch (error) {
router.push('/error')
}
}
return {
navigateToUser,
navigateWithObject,
replaceCurrentRoute,
goBackInHistory,
navigateAfterAction
}
}
}
Here useRouter() provides access to the router instance in the Composition API. The push() method adds new entries to browser history, while replace() replaces the current entry. Navigation can use string paths or route objects with names, parameters, and query strings. The go() method navigates through browser history, and navigation can be conditional based on async operations or user authentication.
Best Practice Note:
This is the same approach we use in CoreUI Vue applications for handling form submissions, authentication flows, and conditional navigation in enterprise user interfaces. Always handle navigation errors and consider user experience when programmatically changing routes, especially in async operations that might fail.



