1. 登錄部分:
- 登錄調(diào)用登錄接口獲取token,并將token存儲在cookie中(js-cookie插件);
- 驗證成功路由跳轉(zhuǎn)到首頁
this.$router.push({ path: '/' })
;
2. 路由跳轉(zhuǎn)前判斷router.beforeEach((to, from, next) => {}
```javascript
router.beforeEach((to, from, next) => { //路由攔截
if (getToken()) { // 如果瀏覽器中有token
if (to.path === '/login') { //判斷是否是去登錄頁
next({ path: '/' })
} else {
if (store.getters.roles.length === 0) { // 判斷當(dāng)前用戶是否已拉取完user_info信息
store.dispatch('GetUserInfo').then(res => { // 拉取user_info
const roles = res.data.roles //roles是數(shù)組,權(quán)限不只是一個
store.dispatch('GenerateRoutes', { roles }).then(() => { // 根據(jù)roles權(quán)限生成可訪問的路由表
router.addRoutes(store.getters.addRouters) // 動態(tài)添加可訪問路由表
next({ ...to, replace: true }) // hack方法 確保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
})
}).catch(() => {
store.dispatch('FedLogOut').then(() => {
Message.error('驗證失敗褂策,請重新登錄')
next({ path: '/login' })
})
})
} else {
// 沒有動態(tài)改變權(quán)限的需求可直接next() 刪除下方權(quán)限判斷 ↓
if (hasPermission(store.getters.roles, to.meta.roles)) {
next()//
} else {
next({ path: '/401', replace: true, query: { noGoBack: true }})
}
// 可刪 ↑
}
}
}else{ //獲取不到瀏覽器的token
if (whiteList.indexOf(to.path) !== -1) { // 在免登錄白名單,直接進入
next()
} else {
next('/login') // 否則全部重定向到登錄頁
}
}
})