JAVASCRIPT
Programmatic Navigation with Vue Router in Vue 3
Learn how to programmatically navigate users to different routes within your Vue 3 application using the Vue Router's `router.push()` method.
// router/index.js (simplified for example)
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';
import UserProfile from '../views/UserProfile.vue';
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/user/:id', name: 'UserProfile', component: UserProfile }
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
// In a Vue component (.vue file)
<template>
<div>
<button @click="goToAbout">Go to About</button>
<button @click="goToUser(123)">Go to User 123</button>
<button @click="replaceRoute">Replace Current Route</button>
</div>
</template>
<script setup>
import { useRouter } from 'vue-router';
const router = useRouter();
const goToAbout = () => {
router.push('/about');
};
const goToUser = (id) => {
router.push({ name: 'UserProfile', params: { id } });
};
const replaceRoute = () => {
// This navigates without adding a new entry to the history stack
router.replace('/home'); // Assuming you have a '/home' route
};
</script>
How it works: This snippet illustrates how to perform programmatic navigation using Vue Router in a Vue 3 application. By importing `useRouter` from `vue-router` in a component's `setup` function, you gain access to the router instance. The `router.push()` method is used to navigate to a new URL, adding it to the browser's history stack. You can pass a string path or a route object (useful for named routes and dynamic parameters). `router.replace()` navigates without pushing a new entry, effectively replacing the current history entry. This is crucial for building dynamic navigation flows, such as after a form submission or a login.