前提:由于公司架构师整合,决定将用户token放跨域cookie里面(axios设置withCredentials: true),前端就无需记录token与用户状态,由此对全局路由的逻辑的改变
关键:
用 【用户信息】判断用户是否登录,
没有用户信息时,获取用户信息(若已登录获取成功,没有登录或失效获取不到用户信息),
然后再进入下一个路由
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/loginBms'] // no redirect whitelist
router.beforeEach(async(to, from, next) => {
// start progress bar
NProgress.start()
// set page title
document.title = getPageTitle(to.name)
// determine whether the user has logged in
const hasUserInfo = store.state.bmsUser.name
if(hasUserInfo){
if(to.path === '/loginBms'){
next({ path: from.path })
NProgress.done()
return false
}
next()
}else{
if(whiteList.includes(to.path)){
next()
return false
}
try {
await store.dispatch('bmsUser/getUserInfo')
const accessRoutes = await store.dispatch('bmsPermission/generateRoutes')
console.log('accessRoutes:',accessRoutes)
router.addRoutes(accessRoutes)
next({ ...to, replace: true })
} catch (error) {
next(`/loginBms?redirect=${to.path}`)
NProgress.done()
}
}
})
router.afterEach(() => {
// finish progress bar
NProgress.done()
})