How to get current route name in VueJs?

In this short article, we will learn how to find out the current route name in VueJS.

To get the current route name and the path of a page we will have to use the router instance provided by VueJS.

However, finding the route name or path is a little different depending on the version of Vue you are using in your project.

Getting current route name in Vue 2

In Vue 2, we have to use the route instance to get the name. To get the name of the current route we have to use this.$route.name.

Example:

<script>
export default {
  computed:{
     routeName(){
       return this.$route.name
    },
  }
};
</script>

Here, we have used computed but you can also use the created() lifecycle hook to get the route name.

To get the path of the route, we can use this.$route.path .

<script>
export default {
  computed:{
     routePath(){
       return this.$route.path 
    },
  }
};
</script>

It will return the path of the route. For example, if you are on the about page, it will return /about (path).

You can also access the route name and path in your Vue template, like this.

<template>
  <div>
    <span>Current Route is {{$route.name}}</span>
    <span>Current Route Path is {{$route.path}}</span>
  </div>
</template>

Get current route name in Vue 3 with Vue Router 4

If you are using Vue 3 along with Vue Router 4, we can use useRoute() or useRouter() to get the current route name.

Using useRoute():

useRoute() returns us the current route location.

import { useRoute } from 'vue-router';
export default {
  setup () {
    const routeName = computed(() => {
      return useRoute().name
    })
    return { routeName }
  }
}

Using useRouter() :

useRouter() returns us the router instance.

import { useRouter } from 'vue-router';
export default {
  setup () {
    const routeName = computed(() => {
      return useRouter().currentRoute.value.name;
    })
    return { routeName }
  }
}

Both useRoute() and useRouter() must be used inside of setup().


Related Topics:

Set URL Query Params In Vue Using Vue-Router

How To Redirect To External Url In Vue

How to open a link in a new tab in Vue?

Scroll to Top