在某些狀況下,當路由跳轉前或跳轉後、進入、離開某一個路由前、後,須要作某些操做,就能夠使用路由鉤子來監聽路由的變化this
全局路由鉤子:code
router.beforeEach((to, from, next) => { //會在任意路由跳轉前執行,next必定要記着執行,否則路由不能跳轉了 console.log('beforeEach') console.log(to,from) // next() }) // router.afterEach((to, from) => { //會在任意路由跳轉後執行 console.log('afterEach') })
單個路由鉤子:
只有beforeEnter,在進入前執行,to參數就是當前路由component
routes: [ { path: '/foo', component: Foo, beforeEnter: (to, from, next) => { // ... } } ]
路由組件鉤子:router
beforeRouteEnter (to, from, next) { // 在渲染該組件的對應路由被 confirm 前調用 // 不!能!獲取組件實例 `this` // 由於當守衛執行前,組件實例還沒被建立 }, beforeRouteUpdate (to, from, next) { // 在當前路由改變,可是該組件被複用時調用 // 舉例來講,對於一個帶有動態參數的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉的時候, // 因爲會渲染一樣的 Foo 組件,所以組件實例會被複用。而這個鉤子就會在這個狀況下被調用。 // 能夠訪問組件實例 `this` }, beforeRouteLeave (to, from, next) { // 導航離開該組件的對應路由時調用 // 能夠訪問組件實例 `this` }