vue的router鉤子函數

路由的鉤子函數總結有6個
全局的路由鉤子函數:beforeEach、afterEach
單個的路由鉤子函數:beforeEnter
組件內的路由鉤子函數:beforeRouteEnter、beforeRouteLeave、beforeRouteUpdate

模塊一:全局導航鉤子函數
1.vue router.beforeEach(全局前置守衛)
 beforeEach的鉤子函數,它是一個全局的before 鉤子函數,
(beforeEach)意思是在 每次每個路由改變的時候都得執行一遍。
它的三個參數:
to: (Route路由對象) 即將要進入的目標 路由對象 to對象下面的屬性: path params query hash fullPath matched name meta(在matched下,可是本例能夠直接用)
from: (Route路由對象) 當前導航正要離開的路由
next: (Function函數) 必定要調用該方法來 resolve 這個鉤子。 調用方法:next(參數或者空) ***   
使用的場景:當登陸的時候(存在權限的時候),咱們須要在router文件下的index.js中寫上如下的代碼:
    router.beforeEach((to, from, next) => {
    <!--存放的token或者判斷的標識(這裏寫的是一個樹形結構的菜單爲例 menuTree是個數組)-->
  let menuTree = JSON.parse(sessionStorage.getItem('menuTree'));
  if (from.name == null || to.name == "Login") {
    next();
  } else {
  next({
        path: '/login',
        query: {redirect: to.fullPath}//將跳轉的路由path做爲參數,登陸成功後跳轉到該路由
    })
    或者:(根據項目需求)
    <!--if (menuTree != null) {-->
    <!--  if (to.fullPath == '/EnergyBox') {-->
    <!--    next({-->
    <!--      path: '/Login'-->
    <!--    })-->
    <!--  }-->
    <!--  next();-->
    } else {
      next({
        path: '/Login'
      })
    }
  }
})
next(無參數的時候): 進行管道中的下一個鉤子,若是走到最後一個鉤子函數,
那麼導航的狀態就是 confirmed (確認的)
next('/') 或者 next({ path: '/' }): 跳轉到一個不一樣的地址。當前的導航被中斷,而後進行一個新的導航。
模塊二:路由獨享的守衛(路由內鉤子)
你能夠在路由配置上直接定義 beforeEnter 守衛:
const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      }
    }
  ]
這些守衛與全局前置守衛的方法參數是同樣的。
 模塊三:組件內的守衛(組件內鉤子)
一、beforeRouteEnter、beforeRouteUpdate、beforeRouteLeave
const Foo = {
  template: `...`,
  beforeRouteEnter (to, from, next) {
    // 在渲染該組件的對應路由被 confirm 前調用
    // 不!能!獲取組件實例 `this`
    // 由於當鉤子執行前,組件實例還沒被建立
  },
  beforeRouteUpdate (to, from, next) {
    // 在當前路由改變,可是該組件被複用時調用
    // 舉例來講,對於一個帶有動態參數的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉的時候,
    // 因爲會渲染一樣的 Foo 組件,所以組件實例會被複用。而這個鉤子就會在這個狀況下被調用。
    // 能夠訪問組件實例 `this`
  },
  beforeRouteLeave (to, from, next) {
    // 導航離開該組件的對應路由時調用
    // 能夠訪問組件實例 `this`
  }  
 使用場景:當一個組件中有一個定時器時, 在路由進行切換的時候, 可以使用beforeRouteLeave將定時器進行清楚, 以避免佔用內存:
    beforeRouteLeave (to, from, next) {  
     window.clearInterval(this.timer) //清楚定時器   
     next()
     }
複製代碼
相關文章
相關標籤/搜索