導航鈎子
vue-router 提供的導航鈎子主要用來攔截導航,讓它完成跳轉或取消。有多種方式可以在路由導航發生時執行鈎子:全局的, 單個路由獨享的, 或者組件級的。
全局鈎子
const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { // do something next(); }); router.afterEach((to, from, next) => { console.log(to.path); });
每個鈎子方法接收三個參數:
- to: Route : 即將要進入的目標 [路由對象]
- from: Route : 當前導航正要離開的路由
- next: Function : 一定要調用該方法來 resolve 這個鈎子。執行效果依賴 next
方法的調用參數。
- next(): 進行管道中的下一個鈎子。如果全部鈎子執行完了,則導航的狀態就是confirmed (確認的)。
- next(false): 中斷當前的導航。如果瀏覽器的 URL 改變了(可能是用戶手動或者瀏覽器后退按鈕),那么 URL 地址會重置到 from
- 路由對應的地址。
- next('/') 或者 next({ path: '/' }): 跳轉到一個不同的地址。當前的導航被中斷,然后進行一個新的導航。
確保要調用 next方法,否則鈎子就不會被 resolved。
組件內的鈎子
let fromPath = ''; export default{ beforeRouteEnter (to, from, next) { // 在渲染該組件的對應路由被 confirm 前調用 // 不!能!獲取組件實例 `this` // 因為當鈎子執行前,組件實例還沒被創建 fromPath = from.path; next(); }, }
詳解vue-router 2.0 常用基礎知識點之導航鈎子 http://www.jb51.net/article/113422.htm
原文來自:https://router.vuejs.org/zh-cn/advanced/meta.html
