對此,vue-router 提供的 beforeEach可以方便地實現全局導航守衛(navigation-guards)。組件內部的導航守衛函數使用相同,只是函數名稱不同(beforeRouteEnter 、beforeRouteUpdate(2.2 新增) 、beforeRouteLeave)。
1、如何設置一個全局守衛
你可以使用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(()=>{ //跳轉失敗頁面 next({ path: '/error', replace: true, query: { noGoBack: true }}) }) } }); export default router
溫馨提示:有些地方為vuex介入調取方法及數據判斷,但由於例子原因就不展示,只提供思路供大家參考。
最后和大家說下如果白名單太多或項目更大時,我們需要把白名單換為vue-router路由元信息:
3、meta字段(元數據)
直接在路由配置的時候,給每個路由添加一個自定義的meta對象,在meta對象中可以設置一些狀態,來進行一些操作。用它來做登錄校驗再合適不過了
{ path: '/actile', name: 'Actile', component: Actile, meta: { login_require: false }, }, { path: '/goodslist', name: 'goodslist', component: Goodslist, meta: { login_require: true }, children:[ { path: 'online', component: GoodslistOnline } ] }
這里我們只需要判斷item下面的meta對象中的login_require是不是true,就可以做一些限制了
router.beforeEach((to, from, next) => { if (to.matched.some(function (item) { return item.meta.login_require })) { next('/login') } else next() })