Reputation: 9722
I'm fairly new to vue.js
and I'm currently trying to setup my different routes. I'm using sub routes, since the "logged in" user will have a different UI than a visitor.
Currently my setup is like this:
routes: [
{
path: '/auth',
name: 'auth',
component: test,
meta: {
auth: false
},
children: [
{
path: 'login',
name: 'login',
component: login
},
{
path: 'signup',
name: 'signup',
component: signup
}
]
},
{
path: '/user',
name: 'user',
component: test,
meta: {
auth: true
},
children: [
{
path: 'profile',
name: 'profile',
component: login
}
]
}
]
While this is working, I'm wondering why child routes don't take over the parents meta
properties. Do I need to assign the meta.auth
to each sub route? Or is there any way to inherit this?
Essentially in the router.beforeEach
, I want to check if the user is authenticated correctly or not. But only on child routes of /user
I'm also coming from an angular
background, so I'm used to nesting routes, not sure if this is the best way in Vue.
Upvotes: 10
Views: 7488
Reputation: 585
With vue-router v.3 to match parent's meta (for example: in beforeEach()
func. ) You need to use to.matched.some()
like this:
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.auth)) {
// ...
next({name:'route-name'})
} else {
next()
}
}
https://router.vuejs.org/guide/advanced/meta.html
Upvotes: 2
Reputation: 9722
To answer my own question: https://github.com/vuejs/vue-router/issues/704
I didn't realise this was deprecated in Vue-router 2.0, it is possible to get the matched route and find the meta there.
Upvotes: 6