Vue-router: Get the parent meta

Created on 30 Sep 2016  路  3Comments  路  Source: vuejs/vue-router

On the previous version of vue-router I was able to apply the session validation directly in the parent, but this not work on the new version?! I have to repeat the meta every route?

The code below shows a simplified version of the code who I'm using:

export const routes = [
  {
    path: '/platform',
    meta: { auth: true },
    component: require('./components/Base.vue'),

    children: [
      // users
      {
        path: '/users',
        name: 'users',
        component: require('./components/Users.vue')
      }
    ]
  }
]

export const startSecurity = router => {
  // get login token from the localStorage
  const token = localStorage.getItem('token')

  // before each transition we check if the route need authentication
  router.beforeEach((route, redirect, next) => {
    // check if the user needs to be authenticated. If the yes, redirect to the
    // login page if the token is null
    if (route.meta.auth && token === null) {
      return redirect({ name: 'login' })
    }

    // check if a logged user should see this page
    if (route.meta.guest && token !== null) {
      return redirect({ name: 'dashboard' })
    }

    // authorize transition
    next()
  })
}

Most helpful comment

Hi, thanks for filling this issue.
In vue-router 2.0 parent and child route records are no longer merged into $route, so in order to access the parent's meta field, you need to iterate through route.matched:

// change this 
if (route.meta.auth && token === null)

// to this
if (to.matched.some(m => m.meta.auth) && token === null)

We'll make sure this is covered in the migration guide, thanks!

All 3 comments

Hi, thanks for filling this issue.
In vue-router 2.0 parent and child route records are no longer merged into $route, so in order to access the parent's meta field, you need to iterate through route.matched:

// change this 
if (route.meta.auth && token === null)

// to this
if (to.matched.some(m => m.meta.auth) && token === null)

We'll make sure this is covered in the migration guide, thanks!

Ok... Thanks for the quick response 馃憤

It's worth noting that this also works when using router.currentRoute:

//change this
if (router.currentRoute.meta.auth)

//to this
if (router.currentRoute.matched.some(route => route.meta.auth))
Was this page helpful?
0 / 5 - 0 ratings