1
votes

I'm using the typical Vue Router configuration as shown in their guide. What i want is to show the name of the shown route, outside of the router-view. So i would need to ask the router which route is active.

I've found in the router API that it has a currentRoute property, which i was hoping would give me the active route, and i would read its name, and then i'm fine from there.

To test this, i imported the router like so:

import router from '@/router.js';

Then tried to read the name of the active route:

data: function(){
    return {
        test: router.currentRoute.name
    }
}

And displaying it with {{ test }}.

It seems like it's sort of doing what i wanted it to, but it's super inconsistent and unreliable. I don't get any errors anywhere, and the route name does not show up, and seemingly does not work. But then (sometimes) if i change something in my component's template, like delete an element, or add an element, and Vue hot-reloads my app, the route name appears and continues working. From there, if i refresh, it won't appear again.

What am i doing wrong, and what is the correct way of reading the active route name?


Subquestion

Would it be a good idea to use router.beforeEach for this? Because that seems to work correctly, but it seems like a wrong approach for this...

1
@kcsujeet thanks for the suggestion, i created a computed property and from it i do: return router.currentRoute.name;. The same thing happens, after a hot-reload the route name shows up, after a refresh it disappears.Digital Ninja

1 Answers

1
votes

A route object represents the state of the current active route. It contains parsed information of the current URL and the route records matched by the URL.

Reference.

You can access current route object through this.$route;.