How to use the Vue <router-link> component

by

Prerequisite

This article was with the assumption that the reader:

  • Has basic knowledge of Javascript
  • Is familiar with Vue Js or any other frontend Javascript framework

Introduction

When building single-page applications (SPAs), you need to tie components displayed to the browser’s Uniform Resource Locator(URL). Various javascript web frameworks have their ways of achieving this. In Vue.js, the <router-link> component is used.  The <router-link> component is used to create clickable links that trigger navigation between different views or routes in your application. This updates the content displayed to the user as the URL path changes.

The router link component is used for seamless management of navigation in Vue.js. It is built on Vue.js component system. The Vue <router-link>  component is highly configurable, making it easy to switch components based on the URL path.

In this piece, we will discuss why the <router-link> component is preferred to the traditional  anchor <a> tag. We will also dive into the basics,  the customization options, and best practices involved in using the <router-link> component. Let’s get started!


Why use the <router-link> over the anchor <a> tag ?

  • Unlike the <a> tag, the <router-link> does not refresh the page.  The <router-link> intercepts the click event so the browser does not reload the page. This allows for a smooth transition between pages that share similar components without reloading.
  • The <router-link> works similarly in the HTML5 history and hash mode. For example, in Internet Explorer 9 (IE9), nothing needs to be changed when the router falls back to history mode.

1.  Install Vue Router

You have to install Vue Router in your Vue.js project before you can use <router-link>. Navigate to your project in your terminal and run the command below.

npm install vue-router  

2. Set Up Vue Router in your Application

Now that you have installed Vue Router in your app, you need to set it up. Let us go through a basic set up:

import { createRouter, createWebHistory } from 'vue-router';
import Home from './views/Home.vue';
import About from './views/About.vue';

const routes = [
  { path: '/home', component: Home },
  { path: '/about', component: About },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;

3. Import the Router into your Main Vue Instance

After you have successfully added the paths and components in the routes array, import the route into the main Vue instance.

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';

createApp(App).use(router).mount('#app');

4. Test the Link

Test the link with the most basic usage. Use the “to” prop to specify the path you want to navigate to. You can either use a string or an object.

  • When using a string, the app will navigate to the route provided to the ‘to’ prop.
<router-link to="/about">About Us</router-link>
  • You can also pass an object to the ‘to’ prop. With this feature, you have more control over the link. Let us specify the query parameters and give a named route using this method.
<router-link :to="{ name: 'about', query: { ref: 'newsletter' } }"> About Us </router-link>

5. Customize the <router-link>

One of the perks of Vue Router is that it allows you to customize the <router-link>. By using some props, you can change the appearance and behavior to match the theme of your application. Let us try out some of those props.

–       The ‘active-class’ prop

This prop is used to apply styling to the link when it is active. For example, the ‘is-active’ class is applied to the link when it is active.

<router-link to="/about" active-class="is-active">About Us</router-link>

–       The ‘exact-active-class’ prop

The ‘exact-active-class’ prop applies specific styling when the route matches exactly.  It is particularly useful when dealing with nested routes, whereas the active-class prop is applied more broadly:

<router-link to="/about" exact-active-class="is-exact-active">About Us</router-link>

–       The ‘replace’ prop

The <router-link> adds a new entry to the browser’s history stack by default. To override this, you can replace the current entry by using the replace prop.

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

–       The ‘tag’ prop

The <router-link/> renders as an anchor <a> tag by default. You can change it to a different HTML element. For example, adding a tag of ‘button’ renders the html element as a button.

<router-link to="/about" tag="button">About Us</router-link>

6. Handle External Links

It is not uncommon to link applications to external links. In such instances, it is recommended to use the anchor tag with the href attribute, as the <router-link> is designed for internal navigations.

<a href="https://train-your-skills.com/" target="_blank" rel="noopener">Visit Example</a>

Perks

Now, you have learnt the basic use cases of the <router-link>. Let’s dive into some peculiar scenarios and see what other things the <router-link> component has to offer.

1. Exact Matching in Multiple Active Links

Vue Router automatically applies an active class to the currently active link when you have multiple links. Override this behavior by using the ‘exact’ prop. The exact prop ensures that the active class is only applied when the route matches exactly.

<router-link to="/about" exact>About Us</router-link>
<router-link to="/about/social-media">Our Social Media</router-link>

With the exact prop, the “About Us” link will only be active when the user is on the ‘ /about’ route, and not when they are on ‘/about/team’.

2. Named Routes

Named routes come in handy when you want to refer to a route by its name instead of its path. You do this by adding a name key in your route object just as shown in the code block below:

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

After doing this, you can reference the named route anytime you use the <router-link> in your application. Instead of passing the route, you just pass the name. Take a look at the code block below:

<router-link :to="{ name: 'about' }">About Us</router-link>

3. Navigation Guards

Navigation guards are functions that run before or after a route is resolved. The Vue <router-link> component allows you to apply them directly using event handlers.

For example, you can intercept the navigation and perform some action before allowing the user to proceed. Check out the code block below:

<router-link
  to="/homepage"
  @click.prevent="checkAuth"
>
  Go to HomePage
</router-link>

<script>
export default {
  methods: {
    checkAuth() {
      if (!this.isAuthenticated) {
        alert('Please log in first!');
        // Perform custom logic or redirection           this.$router.push('/login');
      } else {
        this.$router.push('/homepage');
      }
    },
  },
};
</script>

In the code block above, the ‘checkAuth’ method checks if the user is authenticated. If they are, the app navigates to the homepage route. Otherwise, the user gets taken to the login page.

Conclusion

The <router-link> component is an essential component for managing navigation in Vue.js.It offers flexibility, customization options, and a seamless user experience compared to the traditional anchor tag.

By mastering the use of <router-link>, you can build more dynamic and user-friendly apps with ease. Hope you found this write-up useful.

Happy hacking!

Leave a Comment