Vue.js學習(十四)—— Vue中的導航守衛(路由守衛)
對此,vue-router 提供的 beforeEach可以方便地實現全域性導航守衛(navigation-guards)。元件內部的導航守衛函式使用相同,只是函式名稱不同(beforeRouteEnter 、beforeRouteUpdate(2.2 新增) 、beforeRouteLeave)。 官方文件地址:https://router.vuejs.org/zh-cn/advanced/navigation-guards.html
1、如何設定一個全域性守衛
你可以使用router.beforeEach 註冊一個全域性前置守衛:就是在你router配置的下方註冊
const router = newVueRouter({ ... }) 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。2、一個簡單實用的小例子
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() })