JAVASCRIPT

Programmatic Navigation with Vue Router (Composition API)

Learn to perform programmatic navigation in Vue 3 applications using Vue Router's `useRouter` composable, enabling advanced routing logic for better UX.

// router/index.js
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: '/', name: 'Home', component: Home },
  { path: '/about', name: 'About', component: About },
  { path: '/user/:id', name: 'UserProfile', component: UserProfile, props: true },
  { path: '/:pathMatch(.*)*', name: 'NotFound', redirect: '/' } // Catch-all route
];

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

export default router;

// main.js (Vue Router setup)
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';

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

// views/Home.vue (Example component with programmatic navigation)
<template>
  <div>
    <h1>Home Page</h1>
    <p>Welcome to the home page!</p>
    <button @click="goToAbout">Go to About Page</button>
    <button @click="goToUser(123)">View User 123 Profile</button>
    <button @click="goBack">Go Back</button>
  </div>
</template>

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

const router = useRouter();

function goToAbout() {
  router.push('/about'); // Navigating by path
  // router.push({ name: 'About' }); // Navigating by name is often preferred
}

function goToUser(userId) {
  router.push({ name: 'UserProfile', params: { id: userId } });
}

function goBack() {
  router.go(-1); // Go back one step in history
  // Alternatively: router.back();
}
</script>

// views/UserProfile.vue (Receiving route params)
<template>
  <div>
    <h2>User Profile Page</h2>
    <p>Viewing profile for User ID: {{ id }}</p>
    <button @click="router.push('/')">Back to Home</button>
  </div>
</template>

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

defineProps({
  id: { type: [String, Number], required: true }
});

const router = useRouter();
</script>

// App.vue (Basic navigation links)
<template>
  <nav>
    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link>
  </nav>
  <router-view></router-view>
</template>

<script setup>
// No script needed for basic links
</script>
How it works: This snippet demonstrates programmatic navigation using Vue Router in a Vue 3 application with the Composition API. After setting up routes and installing Vue Router, components can access the router instance using the `useRouter()` composable. The `router.push()` method is used to navigate to a new URL, either by path string or by a named route object with parameters. `router.go()` (or `router.back()`) allows navigating forward or backward in the browser history. This programmatic control is essential for actions like form submissions, redirects after authentication, or dynamic navigation based on user interactions, offering more flexibility than simple `<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