vue中 router.beforeEach() 的用法示例代碼
導航守衛(wèi) 主要是通過跳轉或取消得方式守衛(wèi)導航
- 在前端路由跳轉中,路由跳轉前都是會經過beforeEach,而beforeEach可以通過next來控制到底去哪個路由。
- 根據這個特性我們就可以在beforeEach中設置一些條件來控制路由的重定向。
常見的使用場景有:
1、驗證用戶是否登錄(若未登錄,且當前非登錄頁面,則自動重定向登錄頁面);2、用戶權限;3、用戶輸入的路路徑是否存在,不存在的情況下如何處理,重定向到哪個頁面。
此處呢我使用一個簡單的例子:
當用戶輸入的路徑不存在的情況下,將其重定向到‘/’路徑來說明beforeEach是如何控制路由的。
話不多說,直接看下邊如何實現的(這里我以創(chuàng)建一個名為router-be的項目為例)。
第一步 : 規(guī)定進入路由是否需要權限
@/router/index.js
import A from '@/components/a' { path : '/a', name : 'a', component : A, meta : { // 加一個自定義obj requireAuth : true // 參數 true 代表需要登陸才能進入 A } }
第二步 : 使用vuex 整一個useid
@/assets/store.js
//使用vuex三步走 import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) //這個理論來說 const store = new Vuex.Store({ state:{ userId : '' } }) export default store
第三步 : 使用router.beforeEach()
思路:【 如果(進入這個路由需要權限){ 如果(能獲取到這個用戶的userID){ 就讓這個用戶進入這個路由 }否則{ 就讓這個用戶進入b這個頁面 } } 即將進入的路由不需要權限就能進入 { 就讓這個用戶進入這個路由 } 】 對應代碼: import store from '@/assets/store' //把這個userId獲取過來 router.beforeEach((to,from,next)=>{ if(to.meta.requireAuth){ if(store.state.userId){ next() }else{ next({path:'/b'}) } }else{ next() } })
實現原理
- constrouter=newVueRouter({…})
- router.beforeEach((to,from,next)=>{// …})
- 每個守衛(wèi)方法接受三個參數 :
1.to => route : 即將進入的目標路由對象
2.from => route : 當前導航正要離開的路由
3.next => function: 一定要調用該方法來 resolve這個鉤子,執(zhí)行效果以來 next 方法的調用參數
第四步
- 上一步 /b 路由為 登陸頁面
- 當進入A 頁面之前,需要先請求接口,獲取是否有登錄,然后把userId存在vuex 的state 中
- 當沒有userId 時,則在登錄之后,存一個userId 到state 里
第五步 項目中使用
權限
router.beforeEach((to, from, next) => { console.log(to); // DEBUG: 測試 return next(); const { ldomain } = to.query; if (ldomain) { document.domain = ldomain; } const { LoginPage } = byskConfig; if (!router.getMatchedComponents(to.path).length) { console.log("not page", to, from); return next(byskConfig.NotFoundPage.path); } //驗證權限 if (to.meta.permId && !hasPerms(to.meta.permId)) { console.log("no auth", to, from); return next(LoginPage.path); } //驗證是否登錄 if (to.meta.permId && !getCookie("sid")) { console.log("no login & signout", to, from); return next(LoginPage.path); } if (to.matched.length) { let parentRoute = to.matched[to.matched.length - 1].parent; if ( parentRoute && parentRoute.meta.hasOwnProperty("redirect") && parentRoute.meta.redirect !== to.path) { parentRoute.meta.redirect = to.path; } } next(); });
到此這篇關于vue中 router.beforeEach() 的用法的文章就介紹到這了,更多相關vue router.beforeEach() 內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
關于vue-property-decorator的基礎使用實踐
這篇文章主要介紹了關于vue-property-decorator的基礎使用實踐,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08ElementUI級聯選擇器實現同一父級下最多只能選中一個子級
本文主要介紹了ElementUI級聯選擇器實現同一父級下最多只能選中一個子級,同一父級下的子節(jié)點單選,又可以選擇多個不同父級下的節(jié)點,具有一定參考價值,感興趣的可以了解一下2023-10-10