首先是官方文檔對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: true
、name: '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())
}
}
})