導(dǎo)航鉤子
vue-router 提供的導(dǎo)航鉤子主要用來攔截導(dǎo)航,讓它完成跳轉(zhuǎn)或取消。有多種方式可以在路由導(dǎo)航發(fā)生時執(zhí)行鉤子:全局的, 單個路由獨(dú)享的, 或者組件級的。
全局鉤子
你可以使用 router.beforeEach 注冊一個全局的 before 鉤子:
const router = new VueRouter({ ... })router.beforeEach((to, from, next) => { // ...})當(dāng)一個導(dǎo)航觸發(fā)時,全局的 before 鉤子按照創(chuàng)建順序調(diào)用。鉤子是異步解析執(zhí)行,此時導(dǎo)航在所有鉤子 resolve 完之前一直處于 等待中。
每個鉤子方法接收三個參數(shù):
確保要調(diào)用 next 方法,否則鉤子就不會被 resolved。
同樣可以注冊一個全局的 after 鉤子,不過它不像 before 鉤子那樣,after 鉤子沒有 next 方法,不能改變導(dǎo)航:
router.afterEach(route => { // ...})你可以在路由配置上直接定義 beforeEnter 鉤子:
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, beforeEnter: (to, from, next) => { // ... } } ]})這些鉤子與全局 before 鉤子的方法參數(shù)是一樣的。
組件內(nèi)的鉤子
最后,你可以在路由組件內(nèi)直接定義以下路由導(dǎo)航鉤子:
beforeRouteEnterbeforeRouteUpdate (2.2 新增)beforeRouteLeaveconst Foo = { template: `...`, beforeRouteEnter (to, from, next) { // 在渲染該組件的對應(yīng)路由被 confirm 前調(diào)用 // 不!能!獲取組件實(shí)例 `this` // 因?yàn)楫?dāng)鉤子執(zhí)行前,組件實(shí)例還沒被創(chuàng)建 }, beforeRouteUpdate (to, from, next) { // 在當(dāng)前路由改變,但是該組件被復(fù)用時調(diào)用 // 舉例來說,對于一個帶有動態(tài)參數(shù)的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉(zhuǎn)的時候, // 由于會渲染同樣的 Foo 組件,因此組件實(shí)例會被復(fù)用。而這個鉤子就會在這個情況下被調(diào)用。 // 可以訪問組件實(shí)例 `this` }, beforeRouteLeave (to, from, next) { // 導(dǎo)航離開該組件的對應(yīng)路由時調(diào)用 // 可以訪問組件實(shí)例 `this` }}beforeRouteEnter 鉤子 不能 訪問 this,因?yàn)殂^子在導(dǎo)航確認(rèn)前被調(diào)用,因此即將登場的新組件還沒被創(chuàng)建。
不過,你可以通過傳一個回調(diào)給 next來訪問組件實(shí)例。在導(dǎo)航被確認(rèn)的時候執(zhí)行回調(diào),并且把組件實(shí)例作為回調(diào)方法的參數(shù)。
beforeRouteEnter (to, from, next) { next(vm => { // 通過 `vm` 訪問組件實(shí)例 })}路由元信息
你可以 在 beforeRouteLeave 中直接訪問 this。這個 leave 鉤子通常用來禁止用戶在還未保存修改前突然離開。可以通過 next(false) 來取消導(dǎo)航。
定義路由的時候可以配置 meta 字段:
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, children: [ { path: 'bar', component: Bar, // a meta field meta: { requiresAuth: true } } ] } ]})那么如何訪問這個 meta 字段呢?
首先,我們稱呼 routes 配置中的每個路由對象為 路由記錄。路由記錄可以是嵌套的,因此,當(dāng)一個路由匹配成功后,他可能匹配多個路由記錄
例如,根據(jù)上面的路由配置,/foo/bar 這個 URL 將會匹配父路由記錄以及子路由記錄。
一個路由匹配到的所有路由記錄會暴露為 $route 對象(還有在導(dǎo)航鉤子中的 route 對象)的 $route.matched 數(shù)組。因此,我們需要遍歷 $route.matched 來檢查路由記錄中的 meta 字段。
下面例子展示在全局導(dǎo)航鉤子中檢查 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() // 確保一定要調(diào)用 next() }})以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答