路由重定向问题
需求背景1: 当用户登入系统后,进入某个页面,操作完后单击退出 退出当前页面,再次登录时继续访问当前页面
需求背景2: 用户未登录的情况下,输入某页面的url,会被拦截登录,需要在登录后自动转跳到用户输入的url界面
部分实现代码
const whiteList = ['/login', '/register'] // no redirect whitelist
const loginRoutePath = '/login'
router.beforeEach(async (to, from, next) => {
if (JSON.stringify(store.state.app.oemInfo) == '{}') {
await store.dispatch('getOemInfo')
}
// 网站标题
const title = typeof to.meta.title !== 'undefined' ? to.meta.title + ' - ' : ''
to.meta && (setDocumentTitle(`${title}${store.state.app.oemInfo.siteTitle}`))
// console.log(store.state.permission.infoConfig)
/* has token */
if (storage.get('ACCESS_TOKEN') && !whiteList.includes(to.path)) {
const route = store.getters.addRouters
if (route.length == 0) {
await store.dispatch('getPermissionList')
const routes = store.getters.addRouters
if (routes.length > 0) {
router.addRoutes(store.getters.addRouters)
// 请求带有 redirect 重定向时,登录自动重定向到该地址
let redirect = decodeURIComponent(from.query.redirect || to.path)
if (redirect == '/') {
redirect = store.getters.defaultRoutePath
}
exChangeMenu(redirect)
if (to.path === redirect) {
// set the replace: true so the navigation will not leave a history record
next({ ...to, replace: true })
} else {
// 跳转到目的路由
next({ path: redirect })
}
} else {
if (to.path == loginRoutePath) {
next()
} else {
next({ path: loginRoutePath, replace: true })
}
}
} else {
if (to.path == '/') {
const defaultRoutePath = store.getters.defaultRoutePath || loginRoutePath
to = { ...to, path: defaultRoutePath }
}
exChangeMenu(to.path)
next()
}
} else {
if (whiteList.includes(to.path)) {
next()
} else {
// 这里控制在未登入的情况下输入xxxurl可以通过重定位,在登陆后自动跳转
const newURL = parseParams(to.path, to.query).toString()
next(`/login?redirect=${newURL}`)
NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
}
}
NProgress.done()
})
router.afterEach((to, from) => {
setBreadcrumb(to.path)
NProgress.done() // finish progress bar
})
// 拼url的方法
const parseParams = (uri, params) => {
const paramsArray = []
Object.keys(params).forEach(key => params[key] && paramsArray.push(`${key}=${params[key]}`))
if (uri.search(/\?/) === -1) {
uri += `?${paramsArray.join('&')}`
} else {
uri += `&${paramsArray.join('&')}`
}
return uri
}
login.vue 登录部分代码
async loginSuccess (res) {
const data = await store.dispatch('xxxxx')
if (data) {
resetRoutes()
if (this.redirect != '') {
this.$router.push({
path: this.redirect
})
} else {
this.$router.push({
path: '/'
})
}
this.isLoginError = false
} else {
store.dispatch('Logout')
}
},