1、函數的識別:html
一、router.beforeEach:主函數、高階函數、入口函數;vue
二、匿名參量函數:處理跳轉過程當中的附加邏輯數組
(to, from, next) => {ide
if (to.matched.some(record => record.meta.requiresAuth)) {函數
// this route requires auth, check if logged inui
// if not, redirect to login page.this
if (!auth.loggedIn()) {component
next({router
path: '/login',htm
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next() // 確保必定要調用 next()
}
}
三、next函數:不定參量函數
根據匿名函數的處理結果決定跳轉策略;
由router.beforeEach定義並傳給匿名函數。
四、關係
router.beforeEach建立next;
router.beforeEach引用(to, from, next) =>void
(to, from, next) =>void引用next;
五、二階段高階函數
高階函數分爲兩個階段
2、路由元信息、導航守衛
定義路由的時候能夠配置 meta 字段:
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
children: [
{
path: 'bar',
component: Bar,
// a meta field
meta: { requiresAuth: true }
}
]
}
]
})
那麼如何訪問這個 meta 字段呢?
首先,咱們稱呼 routes 配置中的每一個路由對象爲 路由記錄。路由記錄能夠是嵌套的,所以,當一個路由匹配成功後,他可能匹配多個路由記錄
例如,根據上面的路由配置,/foo/bar 這個 URL 將會匹配父路由記錄以及子路由記錄。
一個路由匹配到的全部路由記錄會暴露爲 $route 對象 (還有在導航守衛中的路由對象) 的 $route.matched 數組。所以,咱們須要遍歷 $route.matched 來檢查路由記錄中的 meta 字段。
下面例子展現在全局導航守衛中檢查元字段:
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() // 確保必定要調用 next()
}
})
https://router.vuejs.org/zh/guide/advanced/meta.html