JAVASCRIPT
Vue 3 Programmatic Navigation with Vue Router 4
Implement programmatic navigation using `router.push`, `router.replace`, and `router.go` in Vue 3 applications with Vue Router 4 for dynamic route changes.
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{ path: '/', component: () => import('../views/Home.vue') },
{ path: '/about', component: () => import('../views/About.vue'), meta: { requiresAuth: true } },
{ path: '/dashboard', component: () => import('../views/Dashboard.vue'), meta: { requiresAuth: true } }
]
const router = createRouter({
history: createWebHistory(),
routes
})
// Global Navigation Guard Example
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !localStorage.getItem('userLoggedIn')) {
// Redirect to login or home if not authenticated
next({ path: '/' });
} else {
next();
}
});
export default router
// AnyComponent.vue
<template>
<div>
<h1>Navigation Example</h1>
<button @click="goToAbout">Go to About (push)</button>
<button @click="replaceWithDashboard">Replace with Dashboard</button>
<button @click="goBack">Go Back</button>
<button @click="simulateLogin">Simulate Login</button>
</div>
</template>
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
const goToAbout = () => {
router.push('/about') // Navigates and adds to history
}
const replaceWithDashboard = () => {
router.replace({ name: 'Dashboard' }) // Navigates and replaces current history entry
}
const goBack = () => {
router.go(-1) // Navigates one step back in history
}
const simulateLogin = () => {
localStorage.setItem('userLoggedIn', 'true');
alert('Logged in! Try navigating to /about or /dashboard');
}
// To use named route for Dashboard, add name: 'Dashboard' to its route object
// { path: '/dashboard', name: 'Dashboard', component: () => import('../views/Dashboard.vue'), meta: { requiresAuth: true } }
</script>
How it works: This snippet demonstrates programmatic navigation and a global navigation guard in Vue Router 4. The `router.beforeEach` guard checks if a route requires authentication (via `meta.requiresAuth`) and redirects unauthenticated users. Within a component, the `useRouter()` hook provides access to the router instance. `router.push()` navigates to a new URL and adds it to the browser history, while `router.replace()` navigates without adding a new entry, replacing the current one. `router.go(-1)` simulates a browser back button click. This allows for dynamic and controlled user flow within your application.