路由攔截應(yīng)用場景

圖片.png

圖片.png
如圖所示,當我們進入一個webapp時,點到我的,表示進入個人中心,但是此時用戶是首次使用的話,他是沒有登錄,這時候是不能直接跳轉(zhuǎn)到個人中心頁面的。我們希望他去登錄頁面登錄以后在進行操作,這時就需要用到路由攔截。vue文檔中稱為導航守衛(wèi)
具體使用
首先在路由定義時加入requireAuth:true
{
path: '/systemNews',
component: SystemNews,
meta: {
title:'系統(tǒng)消息',
requireAuth: true //加在這里
}
}
配置好路由之后,使用vue導航守衛(wèi)
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requireAuth)) {
//if (store.state.token) {
// next();
//}
if (isLogin) {
next();
}else {
next({
path: '/login',
query: {redirect: to.fullPath}
})
}
}else {
next();
}
})
to.matched.some(record => record.meta.requireAuth)
這個表示如果你在定義路由的時候requireAuth為ture則進行路由攔截
代碼很簡單,能直白的看出功能,isLogin表示用戶是否登錄,如果登錄通過驗證,就next()繼續(xù)路由跳轉(zhuǎn),如果沒有通過驗證就跳轉(zhuǎn)到登錄頁面,并且附加上要跳轉(zhuǎn)的地址query: {redirect: to.fullPath},以便登錄后能自動會跳到原本要跳轉(zhuǎn)的路由,也算小小的用戶體驗。當然你如果喜歡可用vuex來驗證也行。