JAVASCRIPT

Perform Programmatic Navigation with Vue Router 4

Learn to navigate programmatically in Vue 3 applications using Vue Router 4's `useRouter` composable and `router.push`, `router.replace` methods for dynamic routing logic.

// src/components/NavigationControls.vue
<template>
  <div>
    <button @click="goToHome">Go to Home</button>
    <button @click="goToUserDetails(123)">View User 123</button>
    <button @click="replaceCurrentRoute">Replace with About</button>
  </div>
</template>

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

const router = useRouter();

const goToHome = () => {
  // Navigates to the home route
  router.push('/');
};

const goToUserDetails = (userId) => {
  // Navigates to a dynamic route with params
  router.push({ name: 'UserDetails', params: { id: userId } });
  // Assuming you have a route defined like:
  // { path: '/users/:id', name: 'UserDetails', component: UserDetails }
};

const replaceCurrentRoute = () => {
  // Replaces the current history entry, so going back won't go to the previous page
  router.replace('/about');
};

// You can also use router.go(n) for history navigation (e.g., router.go(-1) for back)
</script>
How it works: This snippet demonstrates programmatic navigation in Vue 3 using Vue Router 4's `useRouter` composable. It showcases `router.push()` for navigating to new routes (adding to history) and `router.replace()` for navigating without adding a new history entry. This approach is essential for scenarios where navigation depends on user actions, data fetching results, or authentication status, offering greater control than declarative `<router-link>` components.

Need help integrating this into your project?

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

Hire DigitalCodeLabs