How to use named routes with Vue Router?

Named routes in Vue Router provide a convenient way to reference routes by their names instead of using URLs directly.

This is especially useful when you have nested or dynamic routes.

To can use named routes with Vue Router we can do the following:

  1. Define Named Routes:

In your router configuration, define a name for each route using the name property.

  1. Navigate using Names:

Use the router-link component or this.$router.push method with the name of the route to navigate.

Here’s an example of how to use named routes:

// router/index.js

import Vue from 'vue';
import Router from 'vue-router';
import Home from '@/views/Home.vue';
import About from '@/views/About.vue';

Vue.use(Router);

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/about',
      name: 'about',
      component: About
    }
  ]
});

export default router;

In the above code, the home route has a name of 'home'.

And the about route has a name of 'about'.

Now, we can navigate using these named routes:

<!-- Example.vue -->

<template>
  <div>
    <!-- Using router-link component -->
    <router-link :to="{ name: 'home' }">Home</router-link>
    <router-link :to="{ name: 'about' }">About</router-link>
    
    <!-- Using programmatic navigation -->
    <button @click="goToHome">Go to Home</button>
    <button @click="goToAbout">Go to About</button>
  </div>
</template>

<script>
export default {
  methods: {
    goToHome() {
      // Programmatic navigation to the 'home' route
      this.$router.push({ name: 'home' });
    },
    goToAbout() {
      // Programmatic navigation to the 'about' route
      this.$router.push({ name: 'about' });
    }
  }
};
</script>

In the above code we use the router-link component with the :to prop to navigate to the named routes.

And we use the this.$router.push method with an object containing the name of the route to navigate programmatically.

Using named routes makes our code more readable and maintainable, especially in larger applications with many routes.