JAVASCRIPT

Programmatic Navigation and Route Control with Vue Router 4

Learn to perform advanced programmatic navigation in Vue 3 applications using Vue Router's `useRouter` hook for dynamic routing logic, redirects, and history management.

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

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/about',
      name: 'about',
      component: AboutView,
    },
    {
      path: '/user/:id',
      name: 'user',
      component: () => import('../views/UserView.vue'),
      props: true, // Pass route params as props
    },
    {
      path: '/:pathMatch(.*)*', // Catch all 404
      name: 'NotFound',
      component: () => import('../views/NotFound.vue'),
    },
  ],
});

// Example of a navigation guard (optional, but related)
router.beforeEach((to, from) => {
  // If user is not authenticated and tries to access /user, redirect to home
  // if (to.name === 'user' && !isAuthenticated) {
  //   return { name: 'home' };
  // }
});


export default router;

// App.vue (or any component that needs navigation)
<template>
  <nav>
    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link> |
    <router-link to="/user/123">User 123</router-link>
  </nav>
  <router-view />
  <hr>
  <div>
    <h2>Programmatic Navigation:</h2>
    <button @click="goToAbout">Go to About (push)</button>
    <button @click="replaceWithHome">Replace with Home</button>
    <button @click="goToUserWithParams">Go to User 456</button>
    <button @click="goBack">Go Back</button>
    <button @click="goForward">Go Forward</button>
  </div>
</template>

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

const router = useRouter();

const goToAbout = () => {
  router.push('/about');
  // Or with name: router.push({ name: 'about' });
};

const replaceWithHome = () => {
  router.replace({ path: '/' });
  // This will replace the current history entry
};

const goToUserWithParams = () => {
  router.push({
    name: 'user',
    params: { id: '456' },
    // query: { source: 'button' } // Optional query parameters
  });
};

const goBack = () => {
  router.go(-1); // Equivalent to history.back()
};

const goForward = () => {
  router.go(1); // Equivalent to history.forward()
};
</script>

<style>
/* Basic router-link styling */
nav a {
  margin-right: 10px;
}
.router-link-active {
  font-weight: bold;
}
</style>

<!-- Example View Components (e.g., views/HomeView.vue) -->
<template>
  <div>
    <h1>Home View</h1>
  </div>
</template>

<script setup>
// HomeView.vue content
</script>

<!-- views/UserView.vue -->
<template>
  <div>
    <h1>User View</h1>
    <p>User ID: {{ id }}</p>
  </div>
</template>

<script setup>
import { defineProps } from 'vue';

defineProps({
  id: String // Prop passed from router params
});
</script>
How it works: While `<router-link>` provides declarative navigation, Vue Router's `useRouter` hook allows for programmatic navigation, essential for handling navigation after user actions like form submissions, redirects, or dynamic routing based on application state. This snippet demonstrates how to inject the router instance and use methods like `router.push()` to add new entries to the history stack, `router.replace()` to replace the current entry, and `router.go()` to navigate back or forward through the history. It also shows how to pass parameters and use named routes, alongside a basic navigation guard.

Need help integrating this into your project?

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

Hire DigitalCodeLabs