We use cookies to enhance your experience on the site
CodeWorlds

RouterLink and RouterView

Two key Vue Router components are

<RouterLink>
and
<RouterView>
. They're like the control panel and display screen in the NOVA LAB command center.

RouterLink - Navigation

<RouterLink>
is a component that creates navigation links. Unlike a regular
<a>
tag, it doesn't cause a page reload - navigation happens within the SPA.

1<template>
2  <nav>
3    <!-- Basic RouterLink -->
4    <RouterLink to="/">Command Center</RouterLink>
5    <RouterLink to="/mission-control">Mission Control</RouterLink>
6    <RouterLink to="/about">About the Mission</RouterLink>
7  </nav>
8</template>

Named Routes

Instead of a path, you can use a route name - safer and more resistant to URL changes:

1<template>
2  <nav>
3    <!-- Navigation by name -->
4    <RouterLink :to="{ name: 'home' }">Home</RouterLink>
5    <RouterLink :to="{ name: 'mission-control' }">Mission Control</RouterLink>
6  </nav>
7</template>

Active Link Classes

RouterLink automatically adds CSS classes to active links:

  • router-link-active
    - when the path partially matches
  • router-link-exact-active
    - when the path exactly matches
1<template>
2  <RouterLink
3    to="/mission-control"
4    active-class="is-active"
5    exact-active-class="is-exact-active"
6  >
7    Mission Control
8  </RouterLink>
9</template>
10
11<style>
12.router-link-active {
13  color: #00ff88;
14  font-weight: bold;
15}
16
17.router-link-exact-active {
18  border-bottom: 2px solid #00ff88;
19}
20</style>

RouterView - Display

<RouterView>
is where the component corresponding to the current route renders. You place it in the application layout:

1<!-- App.vue -->
2<template>
3  <div class="app">
4    <nav class="main-nav">
5      <RouterLink to="/">Home</RouterLink>
6      <RouterLink to="/mission-control">Mission Control</RouterLink>
7    </nav>
8
9    <!-- The current view appears here -->
10    <main>
11      <RouterView />
12    </main>
13  </div>
14</template>

Navigation changes the content of

<RouterView>
, while the rest of the template (e.g., navigation, header, footer) stays in place.

Go to CodeWorlds