JAVASCRIPT
Programmatic Navigation using Vue Router 4
Control application routing dynamically in Vue 3 by leveraging Vue Router 4's programmatic navigation methods for redirects, back actions, and more.
// router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
const routes = [
{ path: '/', name: 'Home', component: Home },
{ path: '/about', name: 'About', component: () => import('../views/About.vue') },
{ path: '/dashboard', name: 'Dashboard', component: () => import('../views/Dashboard.vue') }
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(router);
app.mount('#app');
// MyComponent.vue
<template>
<div>
<button @click="goToAbout">Go to About Page (push)</button>
<button @click="replaceWithDashboard">Replace with Dashboard</button>
<button @click="goBack">Go Back</button>
<button @click="goToUserDetail(123)">Go to User 123</button>
</div>
</template>
<script setup>
import { useRouter } from 'vue-router';
const router = useRouter();
const goToAbout = () => {
router.push('/about');
// router.push({ name: 'About' }); // Alternative using named route
};
const replaceWithDashboard = () => {
// Replaces current entry in history stack, so 'back' won't go to previous page.
router.replace({ name: 'Dashboard' });
};
const goBack = () => {
router.go(-1); // Same as router.back()
};
const goToUserDetail = (userId) => {
router.push({
path: `/users/${userId}`,
// Optional: Pass query parameters or hash
query: { referrer: 'home' },
hash: '#profile'
});
};
</script>
How it works: This snippet demonstrates programmatic navigation in Vue 3 using Vue Router 4. Beyond declarative `<router-link>` components, the `useRouter()` hook allows developers to imperatively control routing within component logic. Methods like `router.push()` add a new entry to the history stack, `router.replace()` replaces the current entry, and `router.go()` (or `router.back()`) navigates back or forward. This is essential for scenarios like post-login redirects, form submissions, or dynamic navigation based on user actions.