Vue Router 01 🧭 Introduction & Setup — Installing Vue Router, createRouter, RouterView, and RouterLink
Vue Router is the official router for Vue.js. It deeply integrates with the Vue core to make building Single Page Applications (SPAs) with Vue a seamless experience. When building an SPA, you are not actually navigating between different HTML files; instead, you are swapping components in and out of the DOM based on the current URL. Vue Router manages this synchronization, ensuring that the browser’s address bar stays in sync with the visual state of the application.
Setting up Vue Router requires a few architectural pieces to work in concert. You need a router instance created via createRouter, a history implementation to handle the browser’s URL API, a collection of route definitions that map paths to components, and specialized components like RouterLink and RouterView to handle navigation and rendering. Without a router, managing complex navigation logic and the browser’s back/forward history manually would be extremely difficult and error-prone.
This chapter provides a comprehensive guide to the initial setup of Vue Router 4. We will cover the installation process using package managers, the creation of the router instance using the factory function, and the integration of the router into the main Vue application instance. We will also examine the fundamental components that make up the user interface layer of the routing system.
Key point: Vue Router maps browser URLs to specific Vue components through a centralized configuration, allowing the application to update its view and URL without a full page reload while maintaining standard browser behaviors like history and deep linking.
Why exists
The Single Page Application problem.
In traditional web development, clicking a link sends a request to the server, which then returns a whole new HTML page. This causes a “flash” of white and resets the application’s state. Vue Router exists to intercept these link clicks, update the URL via the browser’s History API, and swap components locally without a server round-trip for the document itself.
The State-to-URL mapping problem.
Users expect the URL to represent the current state of the application. If a user is looking at a specific product, they should be able to copy the URL and send it to a friend. Vue Router ensures that the visual hierarchy of your components is reflected in the URL path, making the application “bookmarkable” and “linkable.”
The Browser History problem.
Managing the “Back” and “Forward” buttons in a JavaScript-heavy application is complex. If you simply hide one div and show another, the browser doesn’t know a “navigation” occurred. Vue Router interacts with the browser’s pushState and replaceState APIs to ensure that the user’s navigation history is preserved correctly within the SPA.
The Nested UI problem.
Modern interfaces often have nested levels of navigation—a sidebar that stays constant while a sub-section of the page changes. Vue Router allows for nested route definitions, where a parent route can have its own RouterView to render child components, reflecting the nested structure of the UI in the URL structure.
The Modularization problem.
As applications grow, the logic for determining which view to show can become a tangled mess of v-if and v-else statements. Vue Router provides a declarative way to organize this logic into a dedicated configuration file, decoupling the navigation rules from the component logic.
a. Installation and Instance Creation
The first step in using Vue Router is installing the package and creating the router instance. Vue Router 4 is designed for Vue 3. The installation is typically done via npm or yarn. Once installed, you use the createRouter function to define your routing logic. This function requires two main configuration options: a history mode and a routes array.
# Installing the latest version of Vue Router 4
npm install vue-router@4
The history option determines how the router interacts with the browser’s URL. For most modern applications, createWebHistory() is the preferred choice as it uses the clean HTML5 History API (e.g., example.com/about). The alternatives are createWebHashHistory() (which uses a # in the URL) and createMemoryHistory() (mostly used for Server-Side Rendering or testing).
// router/index.ts
import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
// Define the route records
const routes = [
{
path: '/',
name: 'home',
component: HomeView
}
];
// Create the router instance
const router = createRouter({
history: createWebHistory(), // Uses HTML5 History API
routes // Short for routes: routes
});
export default router;
After creating the router, it must be “installed” into the Vue app instance using the .use() method. This makes the router available globally throughout your components, providing access to routing information and helper components.
// main.ts
import { createApp } from 'vue';
import App from './App.vue';
import router from './router'; // Import the router instance
const app = createApp(App);
app.use(router); // Tell Vue to use the router plugin
app.mount('#app');
By calling app.use(router), you enable the RouterLink and RouterView components globally and inject the $router and $route objects into all components.
b. Route Configuration: Mapping Paths to Components
The routes array is the core configuration of Vue Router. Each entry in the array is a “Route Record.” A basic route record requires a path (the URL string) and a component (the Vue component to display). You can also provide a name, which is highly recommended for “named navigation,” making your code more resilient to URL changes.
import AboutView from '../views/AboutView.vue';
const routes = [
{
path: '/',
name: 'home',
component: () => import('../views/HomeView.vue') // Lazy loading
},
{
path: '/about',
name: 'about',
component: AboutView // Static import
}
];
There are two primary ways to import components for routes: static imports and dynamic (lazy) imports. Static imports include the component in the initial JavaScript bundle, while dynamic imports (() => import(...)) use code-splitting. This means the component’s code is only downloaded when the user actually navigates to that specific route, which significantly improves the initial load time of large applications.
Route paths are case-insensitive by default but can be configured otherwise. The / path usually represents the homepage or entry point of the application. It is standard practice to store these definitions in a dedicated file (e.g., src/router/index.ts) to keep the project organized.
c. Core Components: RouterLink and RouterView
Once the router is configured and installed, you need a way to trigger navigation and a place to render the matched components. Vue Router provides two functional components for this purpose: <RouterLink> and <RouterView>.
<RouterLink> is used for navigation. While you could use a standard <a> tag, RouterLink is preferred because it prevents the browser from reloading the page. It automatically applies an “active” CSS class when its target URL matches the current route, which is essential for building navigation menus that highlight the current page.
<!-- App.vue template -->
<nav>
<!-- Navigates to the root path -->
<RouterLink to="/">Home</RouterLink>
<!-- Navigates using the route name (Best Practice) -->
<RouterLink :to="{ name: 'about' }">About Us</RouterLink>
</nav>
The to prop can be a simple string or a complex object. Using the object syntax with the name property is generally safer because if you decide to change the URL from /about to /about-us later, you only have to update the router configuration, and all your RouterLink components will still work correctly.
<RouterView> acts as a placeholder or “outlet.” It tells Vue Router where to render the component that matches the current URL. Without a RouterView, your components will never appear on the screen, even if the URL changes.
<!-- App.vue template -->
<main>
<!-- The matched component for the current route renders here -->
<RouterView />
</main>
You can have multiple RouterView components in your application if you use nested routes. In that case, the top-level RouterView in App.vue renders the top-level component, which might itself contain another RouterView for its children.
Complete Example Session
// ============================================
// PART 1: COMPONENT DEFINITIONS
// ============================================
// src/views/HomeView.vue
// <template><h1>Welcome Home</h1></template>
// src/views/ContactView.vue
// <template><h1>Contact Us</h1></template>
// ============================================
// PART 2: ROUTER CONFIGURATION
// ============================================
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Home',
// Using an arrow function for lazy loading
component: () => import('../views/HomeView.vue')
},
{
path: '/contact',
name: 'Contact',
component: () => import('../views/ContactView.vue')
}
];
const router = createRouter({
history: createWebHistory(), // Clean URLs without #
routes
});
// ============================================
// PART 3: APP INTEGRATION
// ============================================
import { createApp } from 'vue';
import App from './App.vue';
const app = createApp(App);
app.use(router); // Critical: plugins must be used before mounting
app.mount('#app');
// ============================================
// PART 4: NAVIGATION IN TEMPLATE
// ============================================
/*
<template>
<header>
<nav>
<!-- Standard string path -->
<RouterLink to="/">Home</RouterLink>
<!-- Named route binding -->
<RouterLink :to="{ name: 'Contact' }">Contact</RouterLink>
</nav>
</header>
<main>
<!-- Slot for components -->
<RouterView />
</main>
</template>
*/
The parts above demonstrate the full lifecycle of a Vue Router setup: creating components, defining the mapping in a router instance, registering that instance with the Vue app, and implementing the navigation and rendering outlets in the main template.
Quick Reference
Router Instance Methods
| Method | Purpose | Usage |
|---|---|---|
createRouter | Factory to create the router | createRouter({ ... }) |
createWebHistory | HTML5 History mode | history: createWebHistory() |
createWebHashHistory | Hash mode (uses #) | history: createWebHashHistory() |
app.use(router) | Installs the router plugin | app.use(router) |
Route Record Properties
| Property | Required | Description |
|---|---|---|
path | Yes | The URL path string (e.g., /user) |
component | Yes | The Vue component to render |
name | No | Unique name for the route |
redirect | No | Path to redirect to if matched |
RouterLink Props
| Prop | Type | Description |
|---|---|---|
to | String | Object | Target location (path or name) |
replace | Boolean | Navigates without adding history entry |
active-class | String | CSS class for active link |
custom | Boolean | Allows custom rendering of the link |
Best Practices
✅ Do This:
// Use lazy loading for all view components to keep initial bundle small
const component = () => import('./views/About.vue'); // ✅
// Always name your routes for easier navigation management
const route = { path: '/profile', name: 'user-profile' }; // ✅
// Use object syntax for RouterLink to avoid hardcoded paths
// <RouterLink :to="{ name: 'user-profile' }"> // ✅
// Separate router logic into its own file/directory
// src/router/index.ts // ✅
❌ Don’t Do This:
// Don't use standard <a> tags for internal navigation
// <a href="/about">About</a> (Forces full page reload) // ❌
// Don't forget to add a RouterView in your App.vue
// (Application will show nothing for that route) // ❌
// Don't import all components at the top of the router file
// (Slows down initial application load) // ❌
// Don't use hash history unless you have no control over server
// (Makes URLs look ugly: example.com/#/about) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Empty Page | RouterView is missing in the template | Add <RouterView /> to App.vue |
| Link Reloads Page | Used <a> instead of RouterLink | Replace <a> with <RouterLink to="..."> |
| Router Not Found | Forgot app.use(router) in main.ts | Ensure app.use(router) is called before app.mount() |
| 404 on Refresh | Server not configured for HTML5 History | Configure server to redirect all requests to index.html |
| Case Sensitivity | URL typed in uppercase doesn’t match | Set strict: false or sensitive: false in route |
| Infinite Redirects | redirect loop in route config | Check redirect logic to ensure it reaches a terminal route |
Real-World Examples
1. Basic Static Route
{ path: '/home', component: Home }
2. Named Route with Lazy Loading
{ path: '/about', name: 'About', component: () => import('./About.vue') }
3. Root Path Redirect
{ path: '/', redirect: '/dashboard' }
4. Programmatic Navigation (Setup Script)
const router = useRouter();
router.push('/login');
5. RouterLink with Active Class
<RouterLink to="/" active-class="text-blue-500">Home</RouterLink>
6. Catch-all 404 Route
{ path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound }
7. Passing Props to Route Components
{ path: '/user', component: User, props: { id: 123 } }
8. Using Hash History (Legacy Support)
history: createWebHashHistory()
9. Navigating with Parameters
<RouterLink :to="{ name: 'user', params: { id: 5 } }">User 5</RouterLink>
10. Router Instance in Main file
import router from './router';
createApp(App).use(router).mount('#app');
Visual
The Routing Cycle
┌──────────────────────────────────────────────────────────┐
│ BROWSER URL: /about │
└─────────────┬────────────────────────────────────────────┘
│ 1. Intercepts URL change
▼
┌──────────────────────────────────────────────────────────┐
│ VUE ROUTER INSTANCE │
│ Matches "/about" against routes array │
└─────────────┬────────────────────────────────────────────┘
│ 2. Finds match: { path: '/about', comp: About }
▼
┌──────────────────────────────────────────────────────────┐
│ VUE COMPONENT TREE │
│ <RouterView> inside App.vue │
└─────────────┬────────────────────────────────────────────┘
│ 3. Swaps current content for About.vue
▼
┌──────────────────────────────────────────────────────────┐
│ DOM UPDATED │
│ <h1>About Page</h1> │
└──────────────────────────────────────────────────────────┘
Router Configuration Architecture
┌──────────────────────────┐ ┌──────────────────────────┐
│ main.ts │ │ router/index.ts │
│ ┌────────────────────┐ │ │ ┌────────────────────┐ │
│ │ app.use(router) ├──┼─────►│ │ createRouter(...) │ │
│ └────────────────────┘ │ │ └──────────┬─────────┘ │
└──────────────────────────┘ └─────────────┼────────────┘
│
┌───────────▼──────────┐
│ routes: [] │
│ { path: '/home' } │
│ { path: '/about' } │
└──────────────────────┘
Link vs. View Relationship
┌──────────────────────────────────────────────────────────┐
│ NAVIGATION BAR (RouterLink) │
│ [ Home ] [ Settings ] [ Profile ] │
│ │ │
└────┼─────────────────────────────────────────────────────┘
│ (Click triggers change)
▼
┌──────────────────────────────────────────────────────────┐
│ CONTENT AREA (RouterView) │
│ ┌────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ (Active Component Renders Here) │ │
│ │ │ │
│ └────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Package Name | vue-router |
| Primary Function | createRouter |
| History Hook | createWebHistory |
| Link Component | <RouterLink> |
| View Component | <RouterView> |
| Registration | app.use(router) |
| Best Practice | Named Routes |
| Performance | Lazy Loading |
| Required Prop | to (for Link) |
| Required Prop | path (for Route) |
Key takeaways:
- Vue Router enables SPA navigation. It allows users to switch views without reloading the entire page, improving performance and user experience .
- Initialization requires a factory function.
createRouteris used to define the history mode and the mapping between URL paths and Vue components . - The History API is preferred. Using
createWebHistory()provides clean, standard URLs, though it requires server-side configuration to handle direct entry or refreshes . - Navigation is declarative. Using
<RouterLink>ensures that the application stays in SPA mode, whereas using standard<a>tags breaks the SPA flow . - The RouterView is the outlet. This component is essential; it acts as the dynamic window where your routed components are swapped in and out .
- Lazy loading is a vital optimization. By defining component imports as functions, you ensure that the browser only downloads the code necessary for the current view .
Remember: Setting up Vue Router is the first step in moving from a single-component experiment to a professional, multi-page application. By decoupling your URL structure from your component logic and centralizing navigation rules, you create a scalable architecture that respects the browser’s native history and enables features like deep-linking and state preservation.
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!