路由攔截
當(dāng)某些頁面需要權(quán)限訪問時(shí),可以使用路由攔截對(duì)用戶權(quán)限進(jìn)行判斷。
實(shí)現(xiàn)
在自定義路由時(shí)添加自定義字段 requireAuth,用于判斷用戶是否已經(jīng)登錄,已經(jīng)登錄的用戶可以跳轉(zhuǎn),否則將重定向到登錄頁面。
const router = new Router({
routes:[
{
path: '/',
name: 'Index',
compnent: Index,
meta: {
requireAuth: true
}
}
]
})
vue-router 提供了導(dǎo)航守衛(wèi)來通過跳轉(zhuǎn)或取消的方式守衛(wèi)導(dǎo)航。
導(dǎo)航表示路由正在發(fā)生改變,使用
router.beforeEach()注冊(cè)全局守衛(wèi),在每次導(dǎo)航時(shí)判斷用戶是否已經(jīng)登錄。
router.forEach((to, from, next) => {
if (to.some(r => r.meta.requireAuth)){
if (store.state.token){
next()
} else {
next({
path:'/user/login',
query:{ redirect:to.fullPath }
})
}
} else {
next()
}
})
路由攔截經(jīng)常會(huì)與http請(qǐng)求攔截及響應(yīng)攔截配合使用