當做Vue-cli項目的時候感覺在路由跳轉前做一些驗證,比如登錄驗證,是網站中的普遍需求。
對此,vue-router 提供的 beforeEach可以方便地實現全局導航守衛(navigation-guards)。組件內部的導航守衛函數使用相同,只是函數名稱不同(beforeRouteEnter 、beforeRouteUpdate(2.2 新增) 、beforeRouteLeave)。
官方文檔地址:https://router.vuejs.org/zh-cn/advanced/navigation-guards.html
如何設置一個全局守衛
你可以使用 router.beforeEach 注冊一個全局前置守衛:就是在你router配置的下方注冊
const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { // ... })
當一個導航觸發時,全局前置守衛按照創建順序調用。守衛是異步解析執行,此時導航在所有守衛 resolve 完之前一直處於 等待中。
每個守衛方法接收三個參數:
-
to: Route
: 即將要進入的目標 路由對象 -
from: Route
: 當前導航正要離開的路由 -
next: Function
: 一定要調用該方法來 resolve 這個鈎子。執行效果依賴next
方法的調用參數。-
next()
: 進行管道中的下一個鈎子。如果全部鈎子執行完了,則導航的狀態就是 confirmed (確認的)。 -
next(false)
: 中斷當前的導航。如果瀏覽器的 URL 改變了(可能是用戶手動或者瀏覽器后退按鈕),那么 URL 地址會重置到from
路由對應的地址。 -
next('/')
或者next({ path: '/' })
: 跳轉到一個不同的地址。當前的導航被中斷,然后進行一個新的導航。你可以向next
傳遞任意位置對象,且允許設置諸如replace: true
、name: 'home'
之類的選項以及任何用在router-link
的to
prop 或router.push
中的選項。 -
next(error)
: (2.4.0+) 如果傳入next
的參數是一個Error
實例,則導航會被終止且該錯誤會被傳遞給router.onError()
注冊過的回調。
-
確保要調用 next
方法,否則鈎子就不會被 resolved。
一個簡單實用的小例子:
const router = new VueRouter({ ... }) //這是路由配置,我就不多說了 const whiteList = ['/error', '/register/regindex', '/register/userauthent', '/register/submit'] // 路由白名單 vueRouter.beforeEach(function(to,from,next){ console.log("進入守衛"); if (userInfo.user_id>0){ console.log("登錄成功"); next(); //記得當所有程序執行完畢后要進行next(),不然是無法繼續進行的; }else{ console.log("登錄失敗"); getUserInfo.then(res => { if(res){ if (res.user_id){ if (res.status == 4) { //賬號凍結 next({ path: '/error', replace: true, query: { noGoBack: true } }) } if (res.status == 3) { //認證審核中 next({ path: '/register/submit', replace: true, query: { noGoBack: true } }) } if (res.status != 1 && res.status != 3) { if (!res.mobile ) { next({ path: '/register/regindex', replace: true, query: { noGoBack: true }}) } else { //綁定完手機號了 next({ path: '/register/userauthent', replace: true, query: { noGoBack: true } }) } } next(); //記得當所有程序執行完畢后要進行next(),不然是無法繼續進行的; }else{ if (whiteList.indexOf(to.path) !== -1) { // 在免登錄白名單,直接進入 next(); //記得當所有程序執行完畢后要進行next(),不然是無法繼續進行的; }else{ next({ path: '/register/regindex', replace: true, query: { noGoBack: true }}) } } }else{ } } }).catch((