0
0
Vueframework~5 mins

RouterLink for navigation in Vue

Choose your learning style9 modes available
Introduction

RouterLink helps you move between pages in a Vue app without reloading the whole page. It makes navigation smooth and fast.

When you want to link to another page inside your Vue app.
When you want to keep the app feeling fast by avoiding full page reloads.
When you want to highlight the active page link automatically.
When you want to use navigation that works well with browser history (back/forward buttons).
Syntax
Vue
<RouterLink to="/path">Link Text</RouterLink>
Use the component with the 'to' attribute to specify the target route.
The 'to' attribute can be a string path or an object with route details.
Examples
Simple link to the '/home' route.
Vue
<RouterLink to="/home">Home</RouterLink>
Link using a named route with parameters.
Vue
<RouterLink :to="{ name: 'profile', params: { userId: 123 } }">Profile</RouterLink>
Custom link rendering with active class styling.
Vue
<RouterLink to="/about" custom v-slot="{ navigate, href, isActive }">
  <a :href="href" @click="navigate" :class="{ active: isActive }">About Us</a>
</RouterLink>
Sample Program

This example shows a simple navigation bar using components. Clicking links changes the page without reloading. The active link is styled differently.

Vue
<template>
  <nav>
    <RouterLink to="/" class="nav-link">Home</RouterLink>
    <RouterLink to="/about" class="nav-link">About</RouterLink>
    <RouterLink to="/contact" class="nav-link">Contact</RouterLink>
  </nav>
  <router-view />
</template>

<script setup>
// No script needed for basic navigation
</script>

<style scoped>
.nav-link {
  margin-right: 1rem;
  text-decoration: none;
  color: blue;
}
.nav-link.router-link-active {
  font-weight: bold;
  color: darkblue;
}
</style>
OutputSuccess
Important Notes

RouterLink automatically adds a 'router-link-active' class to the active link for styling.

Use to display the matched page content for the current route.

RouterLink works best with Vue Router properly set up in your app.

Summary

RouterLink creates clickable links for Vue app pages without reloading.

Use the 'to' attribute to specify where the link goes.

Active links get a special CSS class for easy styling.