JAVASCRIPT

Programmatic Navigation using Vue Router 4 in Vue 3

Learn to navigate programmatically between routes in your Vue 3 application using Vue Router's `router.push()` and `router.replace()` methods for enhanced control.

// router/index.js
import { createRouter, createWebHistory } from 'vue-router';

const routes = [
  { path: '/', name: 'Home', component: { template: '<div>Home Page</div>' } },
  { path: '/about', name: 'About', component: { template: '<div>About Us</div>' } },
  { path: '/user/:id', name: 'User', component: { template: '<div>User ID: {{ $route.params.id }}</div>' } }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

export default router;

// main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';

const app = createApp(App);
app.use(router);
app.mount('#app');

// MyNavigationComponent.vue
<template>
  <div>
    <button @click="goToHome">Go to Home (Push)</button>
    <button @click="goToAbout">Go to About (Replace)</button>
    <button @click="goToUser(123)">Go to User 123</button>
    <button @click="goBack">Go Back</button>

    <p>Current Path: {{ $route.path }}</p>
    <router-view></router-view>
  </div>
</template>

<script setup>
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const route = useRoute(); // To access current route info

const goToHome = () => {
  router.push('/');
};

const goToAbout = () => {
  router.replace({ name: 'About' });
};

const goToUser = (id) => {
  router.push({ name: 'User', params: { id: id } });
};

const goBack = () => {
  router.go(-1);
};
</script>
How it works: This snippet demonstrates programmatic navigation using Vue Router 4. After setting up routes and installing the router in `main.js`, you can access the router instance within any component using `useRouter()`. The `router.push()` method navigates to a new URL and pushes the new entry onto the history stack, allowing the user to go back. `router.replace()` also navigates but replaces the current entry in the history stack, preventing a back navigation to the previous route. You can navigate using path strings or route objects (with `name` and `params` for dynamic routes), offering flexible control over routing behavior. `router.go(-1)` simulates a browser back button.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs