Learn Vue.js · 9/13

Navigating the App: Vue Router

8 min read

When building a Single Page Application (SPA) with Vue.js, you reach a point where your application needs more than one page. You have a Home page, an About page, and maybe a User Dashboard. But how do you switch between them without losing the "Single Page" magic?

This is where Vue Router steps in. It is the official routing library for Vue.js, designed to deeply integrate with Vue's core to make building SPAs seamless.

Let's break down how we navigate a Vue application, starting from the core concepts and moving to industry standards.


1. Introduction to Client-Side Routing in Vue

The Definition

Client-side routing is a mechanism where JavaScript running in the browser manages the application's URL and updates the screen by swapping out DOM components, rather than making a request to a server for a new HTML document.

The Problem

In the early days of the web, every time you clicked a link (like <a href="/about">), the browser would:

  1. Throw away the current web page.
  2. Stare at a blank white screen.
  3. Ask the server for the /about HTML page.
  4. Download the new page, re-download the CSS, re-download the JavaScript, and render the page from scratch.

This is incredibly slow and completely destroys the application's current state (like a half-filled form or an open dropdown menu).

The Solution: The Single Page Application (SPA)

Vue Router solves this by taking over the browser's URL bar. When you click a link, Vue Router prevents the browser from making a server request. Instead, it looks at the new URL, finds the Vue component associated with that URL, and swaps it directly into the screen.

Under the Hood: How does the URL change without refreshing the page? Vue Router uses the browser's native HTML5 History API (specifically the pushState method). It allows JavaScript to change the URL in the address bar to literally whatever you want, without triggering a page reload.

Real-life scenario:
Imagine you are visiting a massive museum. Traditional server-side routing is like tearing down the entire museum building, throwing away all the art, and rebuilding the whole structure from scratch just because you wanted to walk from the Egyptian exhibit to the Dinosaurs. Client-side routing is simply walking into the next room while the building stays exactly where it is. It is fast, efficient, and saves a lot of concrete.


2. Defining Routes and Using RouterLink/RouterView

Before we can use Vue Router, we need to install it. The industry standard is to use Vue Router v4 with Vue 3.

Installation (Latest Standard):

bash
npm install vue-router@4

The Definition

  • Router Instance: The main configuration object that holds the history mode and the array of your routes.
  • RouterView (<router-view>): A functional placeholder component provided by Vue Router. It dynamically renders the component that matches the current URL.
  • RouterLink (<router-link>): A component that creates navigation links. It renders as an <a> tag but intercepts the click to prevent the default page reload.

The Problem

We need a standardized way to tell Vue, "When the URL is /about, show the AboutComponent. When it is /, show the HomeComponent." Furthermore, we cannot use standard <a href="/about"> tags, because clicking them will trigger the dreaded full-page reload.

The Solution: Defining the Map

Let's set up our routing logic. In an industry-standard Vue application, this is typically done inside a src/router/index.js (or .ts) file.

Step 1: Create the Router

javascript
// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import AboutView from '../views/AboutView.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: HomeView
  },
  {
    path: '/about',
    name: 'About',
    component: AboutView
  }
]

const router = createRouter({
  // createWebHistory utilizes the HTML5 History API we talked about earlier
  history: createWebHistory(), 
  routes
})

export default router

Step 2: Inject it into the Vue App

javascript
// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

const app = createApp(App)

app.use(router) // Telling Vue to use our routing rules
app.mount('#app')

Step 3: Use RouterLink and RouterView

Now, inside our main App.vue, we place our navigation and our placeholder.

html
<!-- src/App.vue -->
<template>
  <header>
    <nav>
      <!-- Use RouterLink instead of <a> tags -->
      <router-link to="/">Home</router-link>
      <router-link to="/about">About</router-link>
    </nav>
  </header>

  <main>
    <!-- This is the magical placeholder where HomeView or AboutView will appear -->
    <router-view></router-view> 
  </main>
</template>

Fun Fact: If you accidentally use a standard <a href="/about"> tag in your Vue app, it will still work, but you will see the browser tab spinner spin. That spinner is the universal sign of shame in the SPA world. Always use <router-link>!


3. Dynamic Route Matching and URL Parameters

The Definition

Dynamic route matching is a way to map multiple URLs to the exact same component by treating a segment of the URL as a dynamic variable, known as a URL parameter.

The Problem

Imagine you are building a user directory. You have 10,000 users. You want a profile page for each user: /users/1, /users/2, /users/3, and so on.
If you try to hardcode this in your routes array, you will be typing until the year 2045.

The Solution: Dynamic Segments

We can define a route with a dynamic segment using a colon :.

javascript
// src/router/index.js
const routes = [
  {
    path: '/users/:id', // The ':id' is dynamic!
    name: 'UserProfile',
    component: UserProfileView
  }
]

Now, URLs like /users/1 and /users/elon_musk will both render the UserProfileView component.

But how does the component know which user to fetch data for? We need to read that URL parameter. In Vue 3's Composition API, we do this using the useRoute composable.

html
<!-- src/views/UserProfileView.vue -->
<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()
const userData = ref(null)

// Access the dynamic part of the URL via route.params
const fetchUser = async (id) => {
  console.log(`Fetching data for user: ${id}`)
  // Imagine an API call here: await api.getUser(id)
  userData.value = { name: `User ${id}`, role: 'Admin' }
}

onMounted(() => {
  fetchUser(route.params.id)
})

// INDUSTRY STANDARD WARNING:
// If a user navigates from /users/1 to /users/2, Vue Router reuses the SAME component 
// to save memory. The onMounted hook will NOT fire again! 
// We must watch the route parameters to detect changes.
watch(
  () => route.params.id,
  (newId) => {
    fetchUser(newId)
  }
)
</script>

<template>
  <div v-if="userData">
    <h1>{{ userData.name }}'s Profile</h1>
    <p>Role: {{ userData.role }}</p>
  </div>
</template>

4. Nested Routes and Basic Navigation Guards

As your application grows, you will encounter two major requirements: UI layouts within other layouts, and restricting access to certain pages.

Nested Routes

The Definition

Nested routes are routes placed inside other routes, allowing you to render a <router-view> inside a component that is already being rendered by a parent <router-view>.

The Problem

Imagine a User Dashboard. The dashboard has a persistent left sidebar with tabs: "Profile", "Settings", and "Billing". When you click "Settings", you want the right side of the screen to change to the Settings panel, but the left sidebar shouldn't move or reload.

The Solution: The children Array

You can nest routes using the children property in your router configuration.

javascript
// src/router/index.js
const routes = [
  {
    path: '/dashboard',
    component: DashboardLayout, // This component must have its own <router-view>
    children: [
      {
        // Renders at /dashboard/profile
        path: 'profile', 
        component: ProfileView
      },
      {
        // Renders at /dashboard/settings
        path: 'settings',
        component: SettingsView
      }
    ]
  }
]
html
<!-- src/views/DashboardLayout.vue -->
<template>
  <div class="dashboard-container">
    <aside class="sidebar">
      <router-link to="/dashboard/profile">Profile</router-link>
      <router-link to="/dashboard/settings">Settings</router-link>
    </aside>

    <main class="content-area">
      <!-- The nested child (ProfileView or SettingsView) renders right here! -->
      <router-view></router-view>
    </main>
  </div>
</template>

Basic Navigation Guards

The Definition

Navigation guards are functions hooked into the routing lifecycle that execute before a route transition is completed. They can resolve the navigation, reject it, or redirect it to a different URL.

The Problem

You have built a secure /admin panel. You hide the link to it so regular users can't click it. But users are smart (sometimes). A user simply types yoursite.com/admin into their browser's URL bar and hits Enter. Because it is just a URL mapped to a component, Vue Router gladly renders the Admin component. You just got hacked via the URL bar.

The Solution: router.beforeEach

We need a bouncer at the door of our routes. We can use a global before guard to check if a user has the right credentials before letting them pass.

javascript
// src/router/index.js

// ... route definitions ...

// Global Navigation Guard
router.beforeEach((to, from) => {
  // 'to' is the Route object being navigated to
  // 'from' is the Route object being navigated away from

  const isAuthenticated = localStorage.getItem('user_token') // Simplified check

  // If the user wants to go to a protected route and is NOT authenticated
  if (to.name === 'Admin' && !isAuthenticated) {
    console.warn('Bouncer says: You shall not pass!')
    
    // Redirect the user to the login page
    return { name: 'Login' } 
  }

  // If we return nothing, or return true, the navigation proceeds normally.
})

Real-life scenario: Think of Navigation Guards as passport control at an airport.

  • to: Your destination country.
  • from: Your departure country.
  • next / return: The border agent stamping your passport (or rejecting you and sending you back to the terminal).

By utilizing dynamic matching, nested views, and guards, you are now equipped to build massive, scalable, and secure Single Page Applications using Vue Router.


References & Further Reading

To expand your knowledge with official, up-to-date documentation, visit the following:

Challenge

You are tasked with setting up the routing configuration for a user dashboard application using Vue Router. Your goal is to define the routes, implement dynamic matching for user IDs, create a nested routing structure, and secure the dashboard with a navigation guard.

Your Tasks:

  1. Initialize the Router: Create a router instance using createRouter and the createWebHistory mode.
  2. Define Top-Level Routes:
    • Create a route for the path /login with the name Login that maps to the Login component.
    • Create a parent route for the path /users with the name UserLayout that maps to the UserLayout component.
  3. Implement Nested and Dynamic Routes:
    • Inside the /users route, define a children array.
    • Add a dynamic child route with the path :userId. This route should have the name UserDetails and map to the UserDetails component.
    • This dynamic :userId route must itself have two nested children:
      • A route for the path profile with the name UserProfile mapping to the UserProfile component. The full path to this route would be /users/:userId/profile.
      • A route for the path settings with the name UserSettings mapping to the UserSettings component.
  4. Implement a Navigation Guard:
    • Add a global router.beforeEach navigation guard.
    • The guard should check if the user is trying to navigate to a route other than Login.
    • If the destination is not Login and the mock isAuthenticated flag is false, the guard must redirect the user to the Login route by returning the appropriate route object.

Expected result

The final code should correctly define a routes array and a router instance with a navigation guard.

The routes array must contain two top-level route objects:

  • One for /login, with the name 'Login' and component Login.
  • One for /users, with the name 'UserLayout' and component UserLayout. This object must contain a children array with a single dynamic route object for :userId.

The :userId route object must:

  • Have the name 'UserDetails' and component UserDetails.
  • Contain its own children array with two route objects:
    • One for the path profile, with the name 'UserProfile' and component UserProfile.
    • One for the path settings, with the name 'UserSettings' and component UserSettings.

The router constant must be initialized by calling createRouter with an object containing history: createWebHistory() and the defined routes array.

A router.beforeEach guard must be implemented. Its logic should check if to.name !== 'Login' AND !isAuthenticated. If both conditions are true, it must return { name: 'Login' } to redirect. Otherwise, it should not return anything or should return true to allow navigation.

javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.