126

I want to get the name of the current route of vue-router, i have a component menu with navigation to another componentes, so i want to dispaly the name of the current route. I have this:

created(){
    this.currentRoute;
    //this.nombreRuta = this.$route.name;
},
computed:{
    currentRoute:{
        get(){
            this.nombreRuta = this.$route.name;
        }
    }
}

But the label of the name of the route does not change, the label only show the name of the first loaded route. Thank You

EDIT:

enter image description here

Image to show what i want

Isaías Orozco Toledo
  • 1,919
  • 5
  • 19
  • 35

16 Answers16

228

You are using computed incorrectly. You should return the property in the function. See the docs for more information.

Here is your adapted example:

computed: {
    currentRouteName() {
        return this.$route.name;
    }
}

You can then use it like this:

<div>{{ currentRouteName }}</div>

You can also use it directly in the template without using a computed property, like this:

<div>{{ $route.name }}</div>
tony19
  • 125,647
  • 18
  • 229
  • 307
ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87
  • 7
    @ali6p I think, you mean `$router.currentRoute` (with an additional `r` at the end). This command returns the `$route` object. See also https://router.vuejs.org/api/#router-currentroute and https://router.vuejs.org/api/#the-route-object – ssc-hrep3 Apr 10 '19 at 12:26
  • 1
    Yeah, you are right. I use $router.currentRoute.name but I wrote without **r** :) Thank you. So what do you think? I define router in main.js and use $router.currentRoute.name. Only .name doesn't work. – ali6p Apr 11 '19 at 09:12
  • If your template does not get updated with the above computed variable, the problem is probably somewhere else. Are you sure, you are actually updating the route? You might want to ask a new question on StackOverflow and link it here. – ssc-hrep3 Dec 28 '20 at 14:55
  • this example return always "null" why? – Fernando Torres May 22 '21 at 20:29
  • 1
    At this point in time, the right answer is probably `this.$route.path`. Try and `console.log(this.$route)` and see if there is anything else you would prefer. – sshine Apr 26 '22 at 22:11
  • 3
    Make sure before you use `this.$route.name` you have defined the `name` properly on each route in your router – kamasuPaul Sep 21 '22 at 06:10
50

Vue 3 + Vue Router 4

Update 5/03/2021

If you are using Vue 3 and Vue Router 4, here is two simplest ways to get current name of route in setup hook:

Solution 1: Use useRoute

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

Solution 2: Use useRouter

import { useRouter } from 'vue-router';
export default {
  setup () {
    const router = useRouter()
    const currentRouteName = computed(() => router.currentRoute.value.name;)
    return { currentRouteName }
  }
}
KitKit
  • 8,549
  • 12
  • 56
  • 82
  • 2
    Instead of using `setup()`, I just used `computed: { route: () => useRoute() }` and then ``{{ route.name }}`` in the template – commonpike Feb 17 '22 at 11:09
21

I use this...

this.$router.history.current.path
Yurifull
  • 373
  • 2
  • 5
  • 10
    Thanks for your contribution. Can you explain why it works to solve the OP's issue? Why do you "use this"? Explanations help future users, increase long term value, are of higher quality, and are more likely to be upvoted. Consider editing to add more context. – SherylHohman Sep 03 '20 at 22:03
  • This works, but only in Vue 2. Starting with Vue 3, accessing the current route from within `$router` is `.currentRoute.value.path` as described above – phil294 Feb 17 '22 at 00:17
9

In Composition API, this works

import { useRouter } from 'vue-router'

const router = useRouter()

let currentPathObject = router.currentRoute.value; 
 
console.log("Route Object", currentPathObject)

// Pick the values you need from the object
Anirudh
  • 2,767
  • 5
  • 69
  • 119
3

I use this...

this.$route.name
tranmani
  • 51
  • 4
3

I used something like this:

import { useRoute } from 'vue-router';

then declared

const route = useRoute();

Finally if you log route object - you will get all properties I used path for my goal.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Archil Labadze
  • 4,049
  • 4
  • 25
  • 42
2

This is how you can access AND watch current route's name using @vue/composition-api package with Vue 2 in TypeScript.

<script lang="ts">
import { defineComponent, watch } from '@vue/composition-api';

export default defineComponent({
  name: 'MyCoolComponent',
  setup(_, { root }) {
    console.debug('current route name', root.$route.name);

    watch(() => root.$route.name, () => {
      console.debug(`MyCoolComponent- watch root.$route.name changed to ${root.$route.name}`);
    });
  },
});
</script>

I will update this answer once Vue 3.0 and Router 4.0 gets released!

ux.engineer
  • 10,082
  • 13
  • 67
  • 112
2

Using composition API,

<template>
 <h1>{{Route.name}}</h1>
</template>

<script setup>
import {useRoute} from 'vue-router';

const Route = useRoute();
</script>
Mishen Thakshana
  • 1,050
  • 1
  • 14
  • 38
2

In Vue 3.2 using Composition API

<script lang="ts" setup>
  
  import { useRoute } from "vue-router";

  const route = useRoute();

  const currentRouteName = computed(() => {
    return route.name;
  });

</script>

<template>
  <div>
   Using computed:{{currentRouteName}} 
   or without using computed: {{route.name}}
  </div>
</template>
1

In my Laravel app I created a router.js file and I can access the router object in any vue component like this.$route

I usually get the route like this.$route.path

Saddan
  • 1,546
  • 16
  • 19
1
this.$router.currentRoute.value.name;

Works just like this.$route.name.

Skoua
  • 3,373
  • 3
  • 38
  • 51
Illuminati
  • 538
  • 7
  • 22
1

Using Vue 3 and Vue Router 4 with Composition API and computed:

<script setup>
    import { computed } from 'vue'
    import { useRouter } from 'vue-router'

    const router = useRouter()

    // computed
    const currentRoute = computed(() => {
        return router.currentRoute.value.name
    })
</script>

<template>
    <div>{{ currentRoute }}</div>
</template>

⚠ If you don't set a name in your router like so, no name will be displayed:

const routes = [
    { path: '/step1', name: 'Step1', component: Step1 },
    { path: '/step2', name: 'Step2', component: Step2 },
];
Skoua
  • 3,373
  • 3
  • 38
  • 51
1

This is how you can get id (name) of current page in composition api (vue3):

import { useRoute } from 'vue-router';

export function useFetchPost() {
  const currentId = useRoute().params.id;
  const postTitle = ref('');

  const fetchPost = async () => {
        try {
        const response = await axios.get(
      `https://jsonplaceholder.typicode.com/posts/${currentId}`
    );
        postTitle.value = response.data.title;
      } catch (error) {
        console.log(error);
      } finally {
      }
  };

onMounted(fetchPost);

return {
  postTitle,
};

}

Joe L.
  • 4,433
  • 1
  • 19
  • 14
ValeronS
  • 11
  • 2
0

I'm using this method on vue 3 & vue-router 4
It works great!

<script>
import { useRoute } from 'vue-router'

export default {
    name: 'Home',
    setup() {
        const route = useRoute();
        const routeName = route.path.slice(1); //route.path will return /name

        return {
            routeName
        }
    }
};
</script>
<p>This is <span>{{ routeName }}</span></p>
0

I've Tried and it Worked:

Use Following in Your Elements;

{{ this.$route.path.slice(1) }}
Skoua
  • 3,373
  • 3
  • 38
  • 51
0

Vue 3 + Vue Router 4 + Pinia store (or any other place outside of vue components)

@KitKit up there gave an example how to get route if you are using Vue 3 and Vue Router 4 in setup hook. However, what about state management in Pinia store ?

In vue@2 and vue-router@3.5.1: We could have used router.currentRoute.query.returnUrl like so (example in vuex state management):

import router from "@/router";

const state = initialState;
const getters = {};
const actions = { // your actions };
const mutations = {
    loginSuccess(state, user) {
        let returnUrl = "";
        if(router.currentRoute.query.returnUrl != undefined)
            returnUrl = router.currentRoute.query.returnUrl;
    },
};

export default {
    state,
    getters,
    actions,
    mutations,
};

export const authentication = {
    actions: {},
    mutations: {},
};

In vue@3 and vue-router@4: We have to append value to currentRoute like so:

import router from '@/router';

export const authenticationStore = defineStore('authUser', {
    state: (): State => ({
        // your state
    }),
    getters: {
        // your getters
    },
    actions: {
        loginSuccess(user: object) {
            let returnUrl = '';
            if (router.currentRoute.value.query.returnUrl != undefined)
                returnUrl = router.currentRoute.value.query.returnUrl;
        },
    },
});
Kadaj
  • 615
  • 3
  • 13
  • 31