143

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

6
  • Did you try to manually entering the url of your route in the browser address bar? Commented Nov 2, 2018 at 22:53
  • @bgsuello everything works, only i want to show a label in the template of the name of the current route in the title of my navigation menu component Commented Nov 2, 2018 at 22:55
  • 4
    Your getter should return this.$route.name. Commented Nov 2, 2018 at 22:56
  • computed may not be the place to do this, try running a method that sets this.$route.name in the mounted() hook Commented Nov 2, 2018 at 22:58
  • 2
    OR try doing it in the beforeEach hook in the routes file, see this: stackoverflow.com/questions/49685780/… Commented Nov 2, 2018 at 23:00

17 Answers 17

242

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>
Sign up to request clarification or add additional context in comments.

6 Comments

@ali6p I think, you mean $router.currentRoute (with an additional r at the end). This command returns the $route object. See also router.vuejs.org/api/#router-currentroute and router.vuejs.org/api/#the-route-object
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.
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.
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.
Make sure before you use this.$route.name you have defined the name properly on each route in your router
|
64

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 }
  }
}

1 Comment

Instead of using setup(), I just used computed: { route: () => useRoute() } and then {{ route.name }} in the template
20

I use this...

this.$router.history.current.path

2 Comments

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.
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
10

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

1 Comment

This is absolute working with VUEJS 3 with Composition API.
4

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.

Comments

4

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>

Comments

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!

Comments

2

I use this...

this.$route.name

Comments

2

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 },
];

Comments

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

Comments

1

Using composition API,

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

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

const Route = useRoute();
</script>

Comments

1
this.$router.currentRoute.value.name;

Works just like this.$route.name.

Comments

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,
};

}

1 Comment

Although this may have solved your problem, it would be better to leverage readily available local data (via the route object that other answers refer to) rather than relying on an API request.
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>

Comments

0

I've Tried and it Worked:

Use Following in Your Elements;

{{ this.$route.path.slice(1) }}

Comments

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 [email protected]: 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;
        },
    },
});

Comments

0
<script lang="ts" setup>
import { useRouter } from 'vue-router'
const router = useRouter()
const currentRouteName = router.currentRoute.value.fullPath

1 Comment

Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to offer an explanation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.