關於vue導航beforeEach和afterEach的一些應用總結

首先是官方文檔對beforeEach前置導航守衛的一些說明:

用法:

router.beforeEach((to, from, next) => {
  // ...
})

每個守衛方法接收三個參數:

  • to: Route: 即將要進入的目標路由對象

  • from: Route: 當前導航正要離開的路由

  • next: Function: 一定要調用該方法來 resolve 這個鉤子。執行效果依賴 next 方法的調用參數。

    • 1:next(): 進行管道中的下一個鉤子。如果全部鉤子執行完了,則導航的狀態就是 confirmed (確認的)。

    • 2:next(false): 中斷當前的導航。如果瀏覽器的 URL 改變了 (可能是用戶手動或者瀏覽器後退按鈕),那麼 URL 地址會重置到 from 路由對應的地址。

    • 3:next('/') 或者 next({ path: '/' }): 跳轉到一個不同的地址。當前的導航被中斷,然後進行一個新的導航。你可以向 next 傳遞任意位置對象,且允許設置諸如 replace: truename: 'home' 之類的選項以及任何用在 router-link 的 to prop 或 router.push 中的選項。

    • 4:next(error): (2.4.0+) 如果傳入 next 的參數是一個 Error 實例,則導航會被終止且該錯誤會被傳遞給 router.onError() 註冊過的回調。

確保要調用 next 方法,否則鉤子就不會被 resolved

 

下面是一些我寫項目時對beforeEach的應用:

//實現功能是後臺頁面訪問需要token驗證;
router.beforeEach((to, from, next) => {
  if (to.matched.some(m => m.meta.requireAuth)) {//meta是路由自己設置的驗證屬性,判斷需要進行驗證的頁面路由
    if (window.localStorage.token) {//如果本地localstorage裏面有token則執行next()跳轉
      next()
    } else if (to.path !== '/login') {//如果本地localstorage裏沒有token,但訪問的路由不是登錄頁面
      let token = window.localStorage.token
      if (token === '' || token === undefined || token === null) {//token爲空返回登錄頁面
        next({
          name: 'Login'//用法3
        })
        Vue.prototype.$message({
          type: 'error',
          message: '請登錄後再訪問',
          showClose: true
        })
      } else {
        next()
      }
    } else {
      next()
    }
  } else {
    next()
  }
})

 其次是官方關於對後置鉤子afteEach的說明:

你也可以註冊全局後置鉤子,然而和守衛不同的是,這些鉤子不會接受 next 函數也不會改變導航本身: 

router.afterEach((to, from) => {
  // ...
})

下面是我在項目裏對afterEach的一些應用:

//以下實現前臺token過期清空;
router.afterEach((to, from) => {
  if (to.matched.some(m => m.meta.requireAuth)) {
    if ((new Date().getTime() - store.getters.getExpire) >= (localStorage.getItem('userInfo').expire - new Date().getTime()) &&
                store.getters.getExpire !== '') {
      store.dispatch('_removeExpire').then(() => {
        router.push('/login')
      })
    } else {
      store.dispatch('_setExpire', new Date().getTime())
    }
  }
})

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章