JAVASCRIPT

Implement Programmatic Navigation with Vue 3 Router

Learn how to programmatically navigate users within your Vue 3 application using Vue Router's `router.push()` and `router.replace()` methods for flexible route management.

<script setup>
import { useRouter } from 'vue-router'; // Assuming Vue Router is installed and configured

const router = useRouter();

function navigateToHome() {
  router.push('/'); // Navigates to the root route
}

function navigateToProduct(productId) {
  router.push({ name: 'ProductDetail', params: { id: productId } });
}

function replaceCurrentRouteWithAbout() {
  router.replace('/about'); // Replaces the current history entry
}

function goBack() {
  router.go(-1); // Go back one step in history
}

function navigateWithQuery() {
  router.push({ path: '/search', query: { q: 'vue', page: 2 } });
}
</script>

<template>
  <div>
    <h1>Programmatic Navigation</h1>
    <button @click="navigateToHome">Go to Home</button>
    <button @click="navigateToProduct(123)">View Product 123</button>
    <button @click="replaceCurrentRouteWithAbout">Replace with About</button>
    <button @click="goBack">Go Back</button>
    <button @click="navigateWithQuery">Search for 'vue'</button>

    <p>Current Path: {{ router.currentRoute.value.fullPath }}</p>
  </div>
</template>
How it works: This snippet showcases how to control navigation programmatically in a Vue 3 application using Vue Router. It uses `useRouter()` to access the router instance and then demonstrates various methods like `router.push()` to add new entries to the history stack, `router.replace()` to replace the current entry, `router.go()` for navigating history steps, and passing route objects with names, params, and queries for more complex navigation scenarios. This is crucial for actions like form submissions, redirects, or dynamic links.

Need help integrating this into your project?

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

Hire DigitalCodeLabs