JAVASCRIPT
Programmatic Route Navigation with Vue Router in Vue 3
Master programmatic navigation in Vue 3 applications using `useRouter` from Vue Router, enabling dynamic route changes, redirects, and query parameter manipulation.
<!-- NavBar.vue -->
<template>
<button @click="goToHomePage">Go to Home</button>
<button @click="goToAboutPageWithParam">Go to About (ID 123)</button>
<button @click="replaceRoute">Replace Current Route</button>
</template>
<script setup>
import { useRouter } from 'vue-router';
const router = useRouter();
const goToHomePage = () => {
router.push('/');
};
const goToAboutPageWithParam = () => {
router.push({
name: 'About', // Assuming you have a named route 'About'
params: { id: '123' },
query: { source: 'nav' }
});
};
const replaceRoute = () => {
// Replaces the current entry in the history stack
router.replace('/dashboard');
};
</script>
How it works: This snippet demonstrates how to perform programmatic navigation in a Vue 3 application using Vue Router's `useRouter` hook. By calling `router.push()` or `router.replace()`, developers can navigate to different routes without relying on `<router-link>` components. `router.push()` adds a new entry to the history stack, while `router.replace()` replaces the current entry. Both methods support various arguments, including path strings and route objects with names, parameters, and query strings.