tosi
tosi

Reputation: 621

vuejs router - this.$route is always empty on refresh

I'm trying to set the class nav-active to the correct nav element, based from what url you're directly accessing the webapp for the first time.

I have a few routes:

export default new Router({
mode: 'history',
routes: [
    {
    path: '/',
    name: 'home',
    component: () => import('./views/Home.vue')
    },
    {
    path: '/account',
    name: 'account',
    component: () => import('./views/Account.vue')
    }
    ]
});

And this is my navigation bar component (NavBar):

export default {
    name: 'NavBar',
    components: {
        NavLogo,
        NavItem
    },
    data() {
        return {
            navItems: [
                {           /* root navigation */
                    id: 0,
                    type: 'root',
                    name: 'home',
                    route: '/',
                    active: this.$route.name === 'home' }, 
                {
                    id: 1,
                    type: 'root',
                    name: 'account',
                    route: '/account',
                    active: false
                }

        }
    }
}

The state of the active boolean inside navItems determines whether the navigation element should have the nav-active class. I'm trying to use the current route to determine whether active should be true or false, by using it this way:

active: this.$route.name === 'account'

But once for example I enter this dashboard directly from: http://localhost:8000/account this.$route's items are all empty and the path is always /

Help is much appreciated, Thanks

Upvotes: 3

Views: 2612

Answers (1)

cuzox
cuzox

Reputation: 794

You are not tracking this.$route.name changes by default with this approach. Try creating a computed property that resolves to this.$route.name, and use this in your data property declaration. In fact, you can just stick the whole thing in a computed property, since you're unlikely to change this.

export default {
    name: 'NavBar',
    components: {
        NavLogo,
        NavItem
    },
    computed: {
        routeName(){
           return this.$route.name
        },
        navItems(){
            return [
                {           /* root navigation */
                    id: 0,
                    type: 'root',
                    name: 'home',
                    route: '/',
                    active: this.routeName === 'home' }, 
                {
                    id: 1,
                    type: 'root',
                    name: 'account',
                    route: '/account',
                    active: false
                }
            ]
        }
    }
}

Upvotes: 4

Related Questions