Vue 路由守衛(wèi)完整流程實(shí)戰(zhàn)+解析
關(guān)注公眾號(hào), 設(shè)置為 '星標(biāo)' ,更多精彩內(nèi)容,第一時(shí)間獲取

導(dǎo)讀大綱
路由守衛(wèi)分類 全局路由守衛(wèi) 單個(gè)路由守衛(wèi) 組件路由守衛(wèi) 路由守衛(wèi)執(zhí)行的完整過程
路由守衛(wèi)分類
全局路由 單個(gè)路由獨(dú)享 組件內(nèi)部路由 每個(gè)路由守衛(wèi)的鉤子函數(shù)都有 3 個(gè)參數(shù):
to: 進(jìn)入的目標(biāo)路由
from: 離開的路由
next: 控制路由 在跳轉(zhuǎn)時(shí)進(jìn)行的操作,一定要執(zhí)行。它有 4 個(gè)行為:
next(): 鉤子都執(zhí)行完了,進(jìn)入到下一個(gè)路由當(dāng)中。
next(false): 中斷路由進(jìn)入下一個(gè)路由。
next('/'): 根據(jù)你路由跳轉(zhuǎn)判斷條件來進(jìn)入對(duì)應(yīng)的路由,/為路由的path。
next(new Error): 中斷路由跳轉(zhuǎn),錯(cuò)誤會(huì)被傳遞給router.onError()注冊(cè)過的回調(diào)。
全局路由守衛(wèi)
beforeEach(to,from, next)beforeResolve(to,from, next)afterEach(to,from)全局路由直接掛載到
router實(shí)例上。
//全局驗(yàn)證路由
const router = createRouter({
history: createWebHashHistory(),
routes
});
// 白名單, 不需要驗(yàn)證的路由
const whiteList = ['/','/register']
router.beforeEach((to,from,next)=>{
if(whiteList.indexOf(to.path) === 0) {
// 放行,進(jìn)入下一個(gè)路由
next()
} else if(!(sessionStorage.getItem('token'))){
next('/');
} else {
next()
}
})
beforeEach
使用場(chǎng)景
「路由跳轉(zhuǎn)前觸發(fā)」
作用
「常用于登錄驗(yàn)證」
beforeResolve
使用場(chǎng)景
「在 beforeEach 和 組件內(nèi)beforeRouteEnter 之后,afterEach之前調(diào)用。」
afterEach
使用場(chǎng)景
「發(fā)生在beforeEach和beforeResolve之后,beforeRouteEnter之前?!?/strong> 「路由在觸發(fā)后執(zhí)行」
單個(gè)路由獨(dú)享
它只有一個(gè) 鉤子函數(shù),
beforeEnter(to,from,next)
beforeEnter
使用場(chǎng)景
「在beforeEach之后執(zhí)行,和它功能一樣」 ,不怎么常用
{
path:'/superior',
component: Superior,
meta:{
icon:'el-icon-s-check',
title:'上級(jí)文件'
},
beforeEnter:(to,form,next) =>{
}
}
組件路由守衛(wèi)
特點(diǎn):
組件內(nèi)執(zhí)行的鉤子函數(shù)
鉤子函數(shù):
beforeRouteEnter(to,from,next)beforeRouteUpdate(to,from,next)beforeRouteLeave(to,from,next)
beforeRouteEnter
使用場(chǎng)景:
路由進(jìn)入之前調(diào)用。 不能獲取組件 this實(shí)例 ,因?yàn)槁酚稍谶M(jìn)入組件之前,組件實(shí)例還沒有被創(chuàng)建。執(zhí)行順序
beforeEach和獨(dú)享守衛(wèi)beforeEnter之后,全局beforeResolve和全局afterEach之前調(diào)用.
beforeRouteUpdate
使用場(chǎng)景:
在當(dāng)前路由改變時(shí),并且該組件被復(fù)用時(shí)調(diào)用,可以通過this訪問實(shí)例。 當(dāng)前路由query變更時(shí),該守衛(wèi)會(huì)被調(diào)用。
beforeRouteLeave
使用場(chǎng)景:
導(dǎo)航離開該組件的對(duì)應(yīng)路由時(shí)調(diào)用,可以訪問組件實(shí)例this
路由守衛(wèi)執(zhí)行的完整過程
導(dǎo)航被觸發(fā) 執(zhí)行 組件內(nèi)部路由守衛(wèi): beforeRouteLeave執(zhí)行 全局路由守衛(wèi) beforeEach在重用組件內(nèi)部路由守衛(wèi)鉤子 beforeRouteUpdate執(zhí)行 路由中的鉤子 beforeEnter在被激活的組件里調(diào)用 beforeRouteEnter 執(zhí)行 全局的 beforeResolve 守衛(wèi) 。 執(zhí)行 全局的 afterEach 鉤子 beforeCreate created beforeMount mounted 執(zhí)行 beforeRouteEnter的next的回調(diào) ,創(chuàng)建好的組件實(shí)例會(huì)作為回調(diào)函數(shù)的參數(shù)傳入。


React Hook | 必 學(xué) 的 9 個(gè) 鉤子
TypeScript學(xué)習(xí)指南(有PDF小書+思維導(dǎo)圖)
原創(chuàng)不易,素質(zhì)三連

