JAVASCRIPT
Perform Programmatic Navigation with Vue Router 4 in Vue 3
Navigate users programmatically within your Vue 3 application using `router.push()`, `router.replace()`, and `router.go()` from Vue Router 4, enabling dynamic routing.
// router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import AboutView from '../views/AboutView.vue';
import UserProfile from '../views/UserProfile.vue';
const routes = [
{ path: '/', name: 'home', component: HomeView },
{ path: '/about', name: 'about', component: AboutView },
{ path: '/users/:id', name: 'user-profile', component: UserProfile, props: true },
{ path: '/login', name: 'login', component: () => import('../views/LoginView.vue') },
{ path: '/dashboard', name: 'dashboard', component: () => import('../views/DashboardView.vue'), meta: { requiresAuth: true } },
{ path: '/:pathMatch(.*)*', name: 'NotFound', component: () => import('../views/NotFound.vue') }
];
const router = createRouter({
history: createWebHistory(),
routes,
});
// Navigation Guard Example (optional, but good for context)
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !localStorage.getItem('userToken')) {
next({ name: 'login', query: { redirect: to.fullPath } });
} else {
next();
}
});
export default router;
// main.js (or equivalent)
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
createApp(App).use(router).mount('#app');
// App.vue
<template>
<div>
<nav>
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link> |
<router-link :to="{ name: 'user-profile', params: { id: 123 }}">User 123</router-link> |
<button @click="goToDashboard">Go to Dashboard (Auth Required)</button>
<button @click="goBack">Go Back</button>
</nav>
<router-view />
</div>
</template>
<script setup>
import { useRouter } from 'vue-router';
const router = useRouter();
const goToDashboard = () => {
// Simulate login success for demonstration
localStorage.setItem('userToken', 'fake-jwt-token');
router.push({ name: 'dashboard' })
.then(() => console.log('Navigated to dashboard'))
.catch(err => console.error('Navigation error:', err));
// Example of replacing current history entry
// router.replace({ name: 'dashboard' });
};
const goBack = () => {
router.go(-1); // Equivalent to history.back()
};
// Example of navigation on certain conditions
const simulateUserLogin = () => {
const loggedIn = true; // In a real app, this would come from an API
if (loggedIn) {
router.push({ name: 'home' });
} else {
router.push('/login');
}
};
// Call simulateUserLogin() when needed, e.g., after an API response
// simulateUserLogin();
</script>
// views/HomeView.vue, AboutView.vue, UserProfile.vue, LoginView.vue, DashboardView.vue, NotFound.vue would exist.
// Example: views/UserProfile.vue
<template>
<div>
<h1>User Profile</h1>
<p>User ID: {{ id }}</p>
<button @click="navigateToAnotherUser">View User 456</button>
</div>
</template>
<script setup>
import { useRoute, useRouter } from 'vue-router';
import { defineProps } from 'vue';
const props = defineProps({
id: String
});
const router = useRouter();
const navigateToAnotherUser = () => {
router.push({ name: 'user-profile', params: { id: 456 } });
};
</script>
How it works: Beyond declarative `<router-link>`, programmatic navigation is essential for redirecting users after form submissions, handling authentication flows, or responding to specific application events. Vue Router 4 provides `useRouter` to access the router instance within the Composition API, allowing methods like `push()` to navigate to a new URL, `replace()` to navigate without adding a new history entry, and `go()` to move forward or backward in history. Navigation guards can be used in conjunction with programmatic navigation for advanced control over routing.