Vue Routing

Vue Routing (Vue Router)

Modern web applications are "Single Page Applications" (SPAs).

This means the browser never reloads the page; JavaScript just dynamically swaps the components in and out.

To navigate between different pages in an SPA, you need a "Router".


Introducing Vue Router

Vue Router is the official routing library for Vue.js.

It deeply integrates with Vue's core to make building SPAs a breeze.

It handles URL changes, browser history (the back button), and loading the correct component.


The Router View

To display the active page, you must add the <router-view> tag to your main App.vue layout.

Think of this tag as a magical window.

Whenever the URL changes, the router injects the matched component directly into this window!

Router View Setup:

<template>
  <h1>My Application Header</h1>
  

<!-- The page components render here --> <router-view></router-view> </template>


The Router Link

In a standard website, you use <a href="/about"> to navigate, which causes a hard page refresh.

In Vue, you must use the <router-link> component instead to prevent this refresh.

Instead of href, you pass the path to the to attribute.

Router Link Example:

<nav>
  <router-link to="/">Home</router-link>
  <router-link to="/about">About Us</router-link>
</nav>

Dynamic Route Matching

Very often you will need to map routes with dynamic parameters (like user IDs).

You can specify dynamic segments in the route configuration using a colon :.

For example, { path: '/users/:id', component: UserProfile }.

Inside the UserProfile component, you can access this ID via $route.params.id!


Exercise 1 of 2

?

What is the purpose of the <router-view> tag in Vue?

Exercise 2 of 2

?

Why should you use <router-link> instead of standard <a href=""> anchor tags?