vue 路由攔截

爲什麼要設置路由攔截

1.有些頁面組件頁面需要登錄才能操作,不然會發生不可預知的錯誤
2.根據用戶權限配置頁面,若沒有這個權限,則你無法進入,進行攔截

1.路由設置:router/index.js

export default new Router({
routes: [
{
path: ‘/index’,
name: ‘index’,
meta: { //自定義配置
requireAuth: true // 加入此字段 進入頁面前判斷是否需要登陸
},
component: Index
}
]
})

2.路由攔截 main.js(若是父子路由跳到第三點)

//路由攔截
let token = sessionStorage.getItem(‘token’);
//這裏以token爲例 如果用戶登錄了就會獲取到token
router.beforeEach((to,from,next)=>{
if(to.meta.requireAuth){ //爲true 需要通過驗證才能跳入
if(token){ //如果有token 則直接跳入路由
next();
console.log(‘我進入了路由’);
}else{ //否則進入登錄頁 重新登錄
next({
path:’/login’
})
}
}else{ //不是爲登錄才能訪問的頁面直接跳轉
next();
}
})

3.父子路由的配置方法

router.beforeEach((to,from,next)=>{
//因爲直接to.meta.requireAuth是訪問不到的,需要matched去匹配
if(to.matched.some(record => record.meta.requireAuth)){
if(token){ //如果有token 則直接跳入路由
next();
console.log(‘我進入了路由’);
}else{ //否則進入登錄頁 重新登錄
next({
path:’/login’
})
}
}else{ //不是爲登錄才能訪問的頁面直接跳轉
next();
}
})

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章