A function of recognition:
1, router.beforeEach: main function, higher-order functions, entry function;
2, anonymous function parameters: jump, the processing of additional logic
(to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// this route requires auth, check if logged in
// if not, redirect to login page.
if (!auth.loggedIn()) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next () // make sure sure to call the next ()
}
}
3, next functions: the function variable parameter
According to the results of processing anonymous function determines the jump strategy;
router.beforeEach defined and passed by the anonymous function.
4, the relationship
router.beforeEach create next;
router.beforeEach引用(to, from, next) =>void
(to, from, next) =>void引用next;
5, the second stage of higher-order functions
Higher-order functions in two stages
Second, the meta-information routing, navigation guard
Define the route when you can configure the meta fields:
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
children: [
{
path: 'bar',
component: Bar,
// a meta field
meta: { requiresAuth: true }
}
]
}
]
})
So how do you access this meta field it?
First of all, we call each route object routes configuration to route record . Routing record can be nested, so that when a match is successful route, he may match multiple routing records
For example, according to the above routing configuration, / foo / bar will match the URL parent recording and a sub-route the route record.
All routes recorded a route matches to be exposed to $ route.matched array is $ route objects (also guarded the route object in the navigation of) of. Therefore, we need to traverse $ route.matched meta field to check the route record.
The following example shows the global navigation guard check meta fields:
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// this route requires auth, check if logged in
// if not, redirect to login page.
if (!auth.loggedIn()) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next () // make sure sure to call the next ()
}
})
https://router.vuejs.org/zh/guide/advanced/meta.html