vue中router.beforeEach()的簡單用法舉例
導(dǎo)航守衛(wèi) 主要是通過跳轉(zhuǎn)或取消得方式守衛(wèi)導(dǎo)航
在前端路由跳轉(zhuǎn)中,路由跳轉(zhuǎn)前都是會(huì)經(jīng)過beforeEach,而beforeEach可以通過next來控制到底去哪個(gè)路由。根據(jù)這個(gè)特性我們就可以在beforeEach中設(shè)置一些條件來控制路由的重定向。
常見的使用場景有:
1、驗(yàn)證用戶是否登錄(若未登錄,且當(dāng)前非登錄頁面,則自動(dòng)重定向登錄頁面);
2、用戶權(quán)限;
3、用戶輸入的路路徑是否存在,不存在的情況下如何處理,重定向到哪個(gè)頁面。
此處呢我使用一個(gè)簡單的例子:
當(dāng)用戶輸入的路徑不存在的情況下,將其重定向到‘/’路徑來說明beforeEach是如何控制路由的。
話不多說,直接看下邊如何實(shí)現(xiàn)的(這里我以創(chuàng)建一個(gè)名為router-be的項(xiàng)目為例)。
第一步 : 規(guī)定進(jìn)入路由是否需要權(quán)限
@/router/index.js
import A from '@/components/a' { path : '/a', name : 'a', component : A, meta : { // 加一個(gè)自定義obj requireAuth : true // 參數(shù) true 代表需要登陸才能進(jìn)入 A } }
第二步 : 使用vuex 整一個(gè)useid
@/assets/store.js
//使用vuex三步走 import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) //這個(gè)理論來說 const store = new Vuex.Store({ state:{ userId : '' } }) export default store
第三步 : 使用router.beforeEach()
思路:【 如果(進(jìn)入這個(gè)路由需要權(quán)限){ 如果(能獲取到這個(gè)用戶的userID){ 就讓這個(gè)用戶進(jìn)入這個(gè)路由 }否則{ 就讓這個(gè)用戶進(jìn)入b這個(gè)頁面 } } 即將進(jìn)入的路由不需要權(quán)限就能進(jìn)入 { 就讓這個(gè)用戶進(jìn)入這個(gè)路由 } 】 對應(yīng)代碼: import store from '@/assets/store' //把這個(gè)userId獲取過來 router.beforeEach((to,from,next)=>{ if(to.meta.requireAuth){ if(store.state.userId){ next() }else{ next({path:'/b'}) } }else{ next() } })
實(shí)現(xiàn)原理
- constrouter=newVueRouter({…})
- router.beforeEach((to,from,next)=>{// …})
- 每個(gè)守衛(wèi)方法接受三個(gè)參數(shù) :
1.to => route : 即將進(jìn)入的目標(biāo)路由對象
2.from => route : 當(dāng)前導(dǎo)航正要離開的路由
3.next => function: 一定要調(diào)用該方法來 resolve這個(gè)鉤子,執(zhí)行效果以來 next 方法的調(diào)用參數(shù)
第四步
- 上一步 /b 路由為 登陸頁面
- 當(dāng)進(jìn)入A 頁面之前,需要先請求接口,獲取是否有登錄,然后把userId存在vuex 的state 中
- 當(dāng)沒有userId 時(shí),則在登錄之后,存一個(gè)userId 到state 里
第五步 項(xiàng)目中使用
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); } //驗(yàn)證權(quán)限 if (to.meta.permId && !hasPerms(to.meta.permId)) { console.log("no auth", to, from); return next(LoginPage.path); } //驗(yàn)證是否登錄 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(); });
權(quán)限
export function setupPermissionGuard(router) { router.beforeEach(async (to, from, next) => { const { state, commit, dispatch } = store; // TODO: 404 的處理 // 不需要登錄,可訪問 if (to.meta.ignoreAuth === true) { next(); return; } // TODO: 白名單 // 刷新重新登錄 if (!state.appToken) { await dispatch('relogin'); } // 處理token const hasToken = !!state.appToken; if (!hasToken) { // 未登陸,或過期 // 重定向到登錄頁 const redirectData = { path: LOGIN_PATH, replace: true, }; next(redirectData); return; } // 判斷是否有權(quán)限 const hasAuthority = to.meta.permId && hasPerms(to.meta.permId); if (hasAuthority) { // 權(quán)限驗(yàn)證 if (to.meta.ignoreKeepAlive !== true) { // 頁面需要緩存, 添加到緩存 const { cachePages } = state; const { matched } = to; commit('setCachePages', [...cachePages, ...matched.slice(1)]); } next(); return; } next(from.path); // next(); }); router.afterEach((to) => { if (to.meta?.label) { // 設(shè)置頁面`title` document.title = `一立科技 - ${to.meta.label}`; } }); }
總結(jié)
到此這篇關(guān)于vue中router.beforeEach()的簡單用法舉例的文章就介紹到這了,更多相關(guān)vue router.beforeEach()用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
el-table實(shí)現(xiàn)給每行添加loading效果案例
這篇文章主要介紹了el-table實(shí)現(xiàn)給每行添加loading效果案例,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08關(guān)于下拉類型多選組件Vue-Treeselect(鍵名轉(zhuǎn)換)
這篇文章主要介紹了關(guān)于下拉類型多選組件Vue-Treeselect(鍵名轉(zhuǎn)換),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07vue前端項(xiàng)目打包成Docker鏡像并運(yùn)行的實(shí)現(xiàn)
這篇文章主要介紹了vue前端項(xiàng)目打包成Docker鏡像并運(yùn)行的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08解決vue項(xiàng)目打包上服務(wù)器顯示404錯(cuò)誤,本地沒出錯(cuò)的問題
這篇文章主要介紹了解決vue項(xiàng)目打包上服務(wù)器顯示404錯(cuò)誤,本地沒出錯(cuò)的問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11vue router+vuex實(shí)現(xiàn)首頁登錄驗(yàn)證判斷邏輯
這篇文章主要介紹了vue router+vuex實(shí)現(xiàn)首頁登錄判斷邏輯,用于判斷是否登錄首頁,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-05-05VUE前端實(shí)現(xiàn)token的無感刷新方式
這篇文章主要介紹了VUE前端實(shí)現(xiàn)token的無感刷新方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11ant-design-vue動(dòng)態(tài)表格合并案例
這篇文章主要介紹了ant-design-vue動(dòng)態(tài)表格合并案例,文章圍繞主題通過案例詳解展開相關(guān)內(nèi)容,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-08-08