Fields can be configured when configuring routes meta
, and this field is a meta field.
We call routes
each routing object in the configuration a routing record ; routing records can be nested, so when a route is successfully matched, it may have multiple routing records.
For example, the following example will match parent route records as well as child route records.
const router=new VueRouter({
routes:[
{
path:'/foo',
component:Foo,
children:[
{
path:'bar',
cpmponent:Bar,
meta:{ requiresAuth:true }//a meta field
}
]
}
]
})
All route records matched by a route will be exposed as The route.matched array ; therefore, we iterate over $route.matched in the matched array to check the meta field in the route record .
route.beforeEach((to,from,next)=>{
if(to.matched.some(record => record.meta.requiredAuth)){
if(!auth.loggedIn()){
next({
path:'/login',
query:{ redirect:to.fullPath }
})
}else{
next()
}else{
next()//确保一定要调用next()
}
}
}
)