Vue Router 04 🧭 Programmatic Navigation & Active Links — Navigating with push/replace/go and customizing router-link-active classes
While the <RouterLink> component handles the majority of navigation needs by rendering accessible anchor tags, modern web applications frequently require navigation triggered by logic rather than direct user clicks. Whether it is redirecting a user after a successful login, moving to a “Thank You” page after a form submission, or implementing a custom “Back” button, programmatic navigation is an essential tool for any developer. This process involves interacting directly with the router instance to manipulate the browser’s history stack.
In addition to moving between views, providing visual feedback to the user regarding their current location is a fundamental aspect of User Experience (UX). Vue Router automatically tracks which links are “active” based on the current URL and applies specific CSS classes to them. This system is highly configurable, allowing developers to distinguish between “exact” matches and “inclusive” matches, which is particularly useful for nested navigation menus where a parent category remains highlighted while a sub-page is active.
This chapter explores the methods available on the router instance for changing routes via JavaScript, the differences between modifying and replacing history entries, and the nuances of history navigation. We will also dive into the styling system for active links, covering the default behavior of router-link-active and router-link-exact-active, and how to customize these classes globally or on a per-link basis.
Key point: Programmatic navigation uses the push, replace, and go methods to move through the history stack via code, while active links provide automatic UI feedback by applying CSS classes based on URL matching.
Why exists
The Post-Action Redirection problem.
In many workflows, navigation should only occur after an asynchronous task completes, such as an API call. You cannot use a static <RouterLink> for a “Submit” button because you don’t want to navigate if validation fails. Programmatic navigation allows you to wait for a successful response before moving the user to the next screen.
The History Stack Management problem.
Sometimes, you want to navigate to a new page but prevent the user from clicking the “Back” button to return to the previous one (e.g., after logging out or completing a payment). Standard links always “push” to the stack. The replace method exists to swap the current entry with a new one, maintaining a clean and logical history for the user.
The Conditional Logic problem.
Navigation often depends on complex state. For example, a “Dashboard” button might need to send a regular user to /user/dash but an administrator to /admin/dash. Programmatic navigation allows you to calculate the target destination in a JavaScript function before executing the move.
The Visual Hierarchy problem.
Without automatic active classes, developers would have to manually compare window.location.path with every link’s to prop to decide which menu item to highlight. Vue Router exists to automate this comparison, ensuring that the UI correctly reflects the application’s state without manual DOM manipulation.
The Partial Match problem.
In hierarchical navigation, a user might be at /settings/profile. Both the “Settings” link and the “Profile” link should ideally show some level of activation. Vue Router differentiates between “Active” (inclusive) and “Exact Active,” providing two distinct classes that solve the problem of highlighting parent and child routes simultaneously.
The Deep Linking Context problem.
When navigating programmatically, developers often need to pass state or query parameters that aren’t part of the core URL structure but are needed for the next view. The programmatic API supports complex location objects, allowing you to include queries, hashes, and params easily in a way that is more readable than concatenating strings.
a. Navigation Methods: push, replace, and go
The router instance provides three primary methods for navigating: push, replace, and go. In the Composition API, you access these by calling the useRouter() hook. In the Options API, they are available via this.$router.
router.push(location) is the most common method. It adds a new entry to the browser’s history stack. When the user clicks the browser’s back button, they will return to where they were before the push.
import { useRouter } from 'vue-router';
const router = useRouter();
// Navigate to a string path
router.push('/home');
// Navigate with an object (Path)
router.push({ path: '/about' });
// Navigate with an object (Named Route) - Recommended
router.push({ name: 'user', params: { username: 'eduardo' } });
// Navigate with query parameters: /register?plan=private
router.push({ path: '/register', query: { plan: 'private' } });
router.replace(location) behaves exactly like push, but instead of adding a new entry, it replaces the current history entry. This is useful for redirects or “temporary” pages where you don’t want the user to get stuck in a “Back” button loop. You can also trigger this in a <RouterLink> by adding the replace prop.
// Replaces the current URL with /login
// The page the user was just on is removed from history
router.replace({ name: 'login' });
router.go(n) takes an integer as a parameter. It moves the user forward or backward through the history stack by n steps. router.back() and router.forward() are shorthand for router.go(-1) and router.go(1) respectively.
// Go back one record, same as router.back()
router.go(-1);
// Go forward 3 records
router.go(3);
// If the record doesn't exist, it fails silently
router.go(100);
b. Named Routes and Navigation Objects
While you can navigate using string paths like router.push('/user/123'), using “Named Routes” is the industry standard for maintainable Vue applications. A named route uses the name property defined in your route configuration rather than the hardcoded URL string.
// Route Configuration
const routes = [
{
path: '/product/:id',
name: 'product-detail',
component: ProductPage
}
];
// Navigation Logic
const goToProduct = (id: number) => {
router.push({
name: 'product-detail',
params: { id: id.toString() }
});
};
Using names provides several advantages. First, if you decide to change the URL structure (e.g., from /product/:id to /item/:id), you only have to update the router config. Every router.push that uses the name product-detail will automatically use the new URL structure. Second, params are automatically encoded, preventing errors with special characters.
When using a path property in a navigation object, the params property is ignored. If you need to provide params, you must use the name property or manually construct the string in the path.
// ❌ WRONG: params will be ignored
router.push({ path: '/user', params: { id: '123' } });
// ✅ CORRECT: Use name
router.push({ name: 'user', params: { id: '123' } });
// ✅ CORRECT: Construct path manually
router.push({ path: `/user/123` });
The navigation object also supports hash (e.g., { hash: '#section-1' }), which will append the fragment to the URL, allowing you to navigate to specific IDs on a page.
c. Customizing Active Link Classes
Vue Router identifies which <RouterLink> components match the current route and automatically applies two CSS classes: router-link-active and router-link-exact-active.
router-link-active: This class is applied when the current route starts with the link’s path. It is “inclusive.” If you are at/settings/profile, a link to/settingswill have this class.router-link-exact-active: This class is only applied if the URL matches the link’s target exactly. If you are at/settings/profile, a link to/settingswill not have this class.
<style>
/* Style for inclusive matches (e.g., parent categories) */
.router-link-active {
color: blue;
font-weight: bold;
}
/* Style for the specific page the user is on */
.router-link-exact-active {
border-bottom: 2px solid blue;
}
</style>
You can customize these class names globally when creating the router instance if you prefer shorter names or are using a CSS framework like Tailwind or Bootstrap.
const router = createRouter({
history: createWebHistory(),
routes: [...],
linkActiveClass: 'active', // Global override
linkExactActiveClass: 'exact-active'
});
You can also override these classes on a per-link basis using the active-class and exact-active-class props. This is useful when one specific part of your UI (like a sidebar) needs different styling logic than the main navigation bar.
<RouterLink
to="/dashboard"
active-class="bg-gray-100 text-black"
exact-active-class="font-black"
>
Dashboard
</RouterLink>
Complete Example Session
// ============================================
// PART 1: DEFINING THE ROUTER
// ============================================
import { createRouter, createWebHistory } from 'vue-router';
const router = createRouter({
history: createWebHistory(),
linkActiveClass: 'is-active', // Custom global class
routes: [
{ path: '/', name: 'home', component: () => import('./Home.vue') },
{ path: '/login', name: 'login', component: () => import('./Login.vue') },
{ path: '/profile/:id', name: 'profile', component: () => import('./Profile.vue') }
]
});
// ============================================
// PART 2: THE COMPOSITION API SETUP
// ============================================
/*
<script setup>
import { useRouter } from 'vue-router';
const router = useRouter();
// ============================================
// PART 3: BASIC PUSH (HISTORY ENTRY)
// ============================================
const goHome = () => router.push('/');
// ============================================
// PART 4: NAMED ROUTE NAVIGATION
// ============================================
const viewProfile = (id) => {
router.push({ name: 'profile', params: { id } });
};
// ============================================
// PART 5: NAVIGATION WITH QUERIES
// ============================================
const search = (term) => {
router.push({ path: '/search', query: { q: term } });
};
// ============================================
// PART 6: REPLACE (NO HISTORY ENTRY)
// ============================================
const handleLogout = () => {
// User cannot go "Back" to the authenticated profile
router.replace({ name: 'login' });
};
// ============================================
// PART 7: HISTORY TRAVEL (BACK/FORWARD)
// ============================================
const goBack = () => router.back();
// ============================================
// PART 8: HANDLING ASYNC NAVIGATION
// ============================================
const submitForm = async () => {
const success = await api.saveData();
if (success) {
router.push({ name: 'home' });
}
};
// ============================================
// PART 9: LINK STYLING IN TEMPLATE
// ============================================
/*
<template>
<nav>
<!-- Uses global 'is-active' class -->
<RouterLink to="/">Home</RouterLink>
<!-- Uses per-link override -->
<RouterLink to="/login" active-class="text-red-500">Login</RouterLink>
</nav>
</template>
*/
// ============================================
// PART 10: REPLACING IN TEMPLATE
// ============================================
/*
<RouterLink to="/login" replace>Switch to Login</RouterLink>
*/
The parts above showcase the complete workflow of programmatic navigation, from instance configuration and custom classes to complex async redirects and history manipulation.
Quick Reference
Programmatic API Methods
| Method | Argument | History Behavior |
|---|---|---|
push | string | object | Adds new entry to stack |
replace | string | object | Swaps current entry in stack |
go | number (delta) | Moves through existing stack |
back | (none) | Equivalent to go(-1) |
forward | (none) | Equivalent to go(1) |
Navigation Object Properties
| Property | Type | Usage |
|---|---|---|
path | string | Absolute path (e.g. /user) |
name | string | Matches route name property |
params | object | For dynamic segments (req. name) |
query | object | Appends ?key=val to URL |
hash | string | Appends #fragment to URL |
RouterLink Active Props
| Prop | Purpose | Example |
|---|---|---|
active-class | Override inclusive class | active-class="open" |
exact-active-class | Override exact class | exact-active-class="here" |
replace | Call router.replace | <RouterLink replace ...> |
Best Practices
✅ Do This:
// Prefer named routes over path strings for better maintenance
router.push({ name: 'user-details', params: { id: '5' } }); // ✅
// Use replace for redirects after actions like Logout
router.replace({ name: 'home' }); // ✅
// Extract router logic into methods for cleaner templates
const goBack = () => router.back(); // ✅
// Use CSS for active links instead of manual logic
// .router-link-active { color: orange; } // ✅
❌ Don’t Do This:
// Don't mix 'path' and 'params' in the same object
router.push({ path: '/user', params: { id: '5' } }); // ❌
// Don't use window.location.href to navigate (reloads page)
window.location.href = '/about'; // ❌
// Don't hardcode logic to check if a link is active
// (Let Vue Router handle classes automatically) // ❌
// Don't use push for sensitive redirects (e.g. login success)
// Use replace so user can't go back to login form // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Params Ignored | Using path instead of name in object | Use name: 'routeName' when passing params |
| Navigation Lag | Navigating inside a loop or before async ends | Use await or call router.push after logic |
| Infinite Redirects | Navigation guard logic is flawed | Check to.path before calling next() or push |
| Active Class Mismatch | Nested route paths overlapping | Use router-link-exact-active for precise styling |
| No History Travel | router.go value exceeds stack size | Check history length or use fail-safe logic |
| Styling Not Applying | Global class override used incorrectly | Ensure linkActiveClass matches your CSS |
Real-World Examples
1. Login Success Redirect
await auth.login();
router.push('/dashboard');
2. Logout and Replace
auth.logout();
router.replace('/login');
3. Back Button Implementation
<button @click="$router.back()">Go Back</button>
4. Filter Results via Query
router.push({ query: { category: 'electronics', sort: 'desc' } });
5. Section Anchor Navigation
router.push({ hash: '#pricing-table' });
6. Admin Panel Inclusive Active
.router-link-active { border-left: 4px solid blue; }
7. Modal “Close” to Previous Route
const close = () => router.back();
8. Redirect on 404 Guard
if (!pageExists) router.replace({ name: '404' });
9. Dynamic Dashboard per Role
const target = user.isAdmin ? 'admin-dash' : 'user-dash';
router.push({ name: target });
10. Navigating from a Pinia Store
// Inside store action
this.router.push('/success');
Visual
History Stack: Push vs. Replace
┌──────────────────────────────────────────────────────────┐
│ HISTORY STACK BEFORE │
│ [ Home ] -> [ Product List ] -> [ Current: Item A ] │
└──────────────────────────────────────────────────────────┘
ROUTER.PUSH('/Item B') ROUTER.REPLACE('/Item B')
│ │
▼ ▼
┌──────────────────────────┐ ┌──────────────────────────┐
│ [ Home ] │ │ [ Home ] │
│ [ Product List ] │ │ [ Product List ] │
│ [ Item A ] │ │ [ Item B ] (Replaced A) │
│ [ Item B ] (New) │ │ │
└──────────────────────────┘ └──────────────────────────┘
Inclusive vs. Exact Matching
┌──────────────────────────────────────────────────────────┐
│ CURRENT URL: /settings/notifications │
└──────────────────────────────────────────────────────────┘
LINK TO: /settings LINK TO: /settings/notifications
┌──────────────────────────┐ ┌──────────────────────────┐
│ router-link-active │ │ router-link-active │
│ [ YES ] │ │ [ YES ] │
├──────────────────────────┤ ├──────────────────────────┤
│ router-link-exact-active │ │ router-link-exact-active │
│ [ NO ] │ │ [ YES ] │
└──────────────────────────┘ └──────────────────────────┘
Programmatic Navigation Flow
┌─────────────────────┐ ┌───────────────────────────┐
│ Action (Button) │─────►│ JS Logic (Component) │
└─────────────────────┘ └─────────────┬─────────────┘
│
┌─────────────▼─────────────┐
│ ROUTER INSTANCE │
│ (push, replace, back) │
└─────────────┬─────────────┘
│
┌─────────────▼─────────────┐
│ URL BAR & HISTORY │
│ (State Updates) │
└───────────────────────────┘
Summary
| Item | Value |
|---|---|
| Add to History | router.push() |
| Overwrite History | router.replace() |
| Step Backward | router.back() |
| Step Forward | router.forward() |
| Jump History | router.go(n) |
| Inclusive CSS | router-link-active |
| Exclusive CSS | router-link-exact-active |
| Global Config | linkActiveClass |
| Link Prop | active-class |
Key takeaways:
- Use programmatic navigation for logic-driven moves. While
<RouterLink>is for user clicks, methods likepushandreplaceallow you to navigate based on API responses or complex application state . - Always prefer Named Routes. Navigating by name makes your application more resilient to URL structure changes and handles parameter encoding automatically .
pushadds,replaceswaps. Usepushfor standard navigation where the back button should work, andreplacefor redirects where the user shouldn’t return to the previous state .- Active classes provide instant feedback. Vue Router applies classes automatically, allowing you to style the user’s current location without writing manual comparison logic .
- Understand the difference between Active and Exact.
router-link-activeis great for hierarchical or sidebar navigation, whileexact-activeis necessary for specific page highlighting . - Composition API uses
useRouter. In modern Vue, you obtain the router instance via the hook, giving you clean access to all navigation methods within yoursetupblock .
Remember: Programmatic navigation and active links are the two halves of a responsive navigation system. One handles the “how” and “when” of moving through the application, while the other handles the “where am I” of the user interface. Together, they create a seamless, predictable flow for the user.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!