JAVASCRIPT
Vue Router 4 Programmatic Navigation
Implement dynamic navigation in your Vue 3 application using Vue Router's programmatic methods like `router.push()` for seamless user experience.
// router/index.js (example setup)
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';
const routes = [
{ path: '/', name: 'Home', component: Home },
{ path: '/about', name: 'About', component: About },
{ path: '/users/:id', name: 'UserProfile', component: () => import('../views/UserProfile.vue') },
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
// src/components/NavigationControls.vue (example usage)
<script setup>
import { useRouter } from 'vue-router';
const router = useRouter();
const goToHomePage = () => {
router.push({ name: 'Home' }); // Navigate by name
};
const goToAboutPage = () => {
router.push('/about'); // Navigate by path string
};
const goToUser = (userId) => {
router.push({ name: 'UserProfile', params: { id: userId } }); // Navigate with params
};
const replaceCurrentRoute = () => {
router.replace('/login'); // Replaces current entry in history
};
const goBack = () => {
router.go(-1); // Go back one step in history
};
</script>
<template>
<div>
<button @click="goToHomePage">Go to Home</button>
<button @click="goToAboutPage">Go to About</button>
<button @click="goToUser(123)">Go to User 123</button>
<button @click="replaceCurrentRoute">Replace with Login</button>
<button @click="goBack">Go Back</button>
</div>
</template>
How it works: Vue Router provides several methods for programmatic navigation, allowing you to control routing dynamically based on user actions or application logic. `router.push()` navigates to a new URL and adds an entry to the history stack, while `router.replace()` navigates without adding a new entry. `router.go()` allows moving forward or backward in the history. This snippet demonstrates navigating by route name, path string, and passing route parameters programmatically.