How to get current route name in VueJs?
Find out how to get the current name of the route and the path in Vue 2 and Vue 3.
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
Related Posts
Easy Way to use localStorage with Vue
Short article on how to use local storage with Vue and learn saving and storing data in local storage with the setItem() and getItem() methods.
Force update Vue to Reload/Rerender component
Short tutorial on how to correctly force update Vue.js component to reload or rerender. The component is reinitialized without having to do a browser refresh.
Set and get cookies in a browser in Vue App
Find out how to set and get cookies in a browser for your webpage in Vue using vue-cookies package.
Save vuex state after page refresh in Vue App
Short tutorial on how to save (or persist) data in a vue application using Vuex and vuex-persist npm package.
