项目是基于vue-element-admin来写的。
具体的动态路由实现请参考,上一篇文章,此文章主要介绍动态重定向。
src/promission.js
import router from './router'
import store from './store'
// import { Message } from 'element-ui'
import { getAccessToken } from '@/utils/auth'
const whiteList = ['/login'] //没有重定向的白名单
router.beforeEach(async (to, from, next) => {
const hasToken = getAccessToken()
if (hasToken) { //是否存在token
if (to.path === '/login') { //访问路径是否为登录页面
next({ path: 'index' }) //重定向到一个虚拟页面
} else {
// 获取到的静态路由 + 动态动态
const hasGetPermissionRoutes = store.getters.permission_routes && store.getters.permission_routes.length > 0
// 判断是否第一次登陆
if (hasGetPermissionRoutes) {
next()
} else {
try {
// const roles = store.state.user.role,原文档写法,但是这样的话 会导致刷新后,数据丢失
const roles = JSON.parse(localStorage.getItem('role'))
const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
let indexRou = [{ path: '/index', redirect: accessRoutes[0].redirect }] //配置跳转路由
router.addRoutes(indexRou) //配置的路由添加到addRouter
await router.addRoutes(accessRoutes) //异步加载动态路由
next({ ...to, replace: true })
} catch (error) {
// 删除令牌并进入登录页面重新登录
await store.dispatch('user/removeAccessToken')
// Message.error(error || 'Has Error')
next(`/login?redirect=${to.path}`)
}
}
}
} else {
// // has no token
if (whiteList.indexOf(to.path) !== -1) {
// in the free login whitelist, go directly
next()
} else {
// other pages that do not have permission to access are redirected to the login page.
next(`/login?redirect=${to.path}`)
}
// next() //重定向至login页面
}
})
src/login/userlogin
登录模块
this.$refs.loginForm.validate((valid) => {
if (valid) {
this.loading = true;
this.$store
.dispatch("user/login", this.loginForm)
.then((res) => {
this.$router.push({ path: 'index' }); //重定向到虚拟页面,具体的跳转由src/promission做处理
this.loading = false;
})
.catch(() => {
this.loading = false;
});
} else {
return false;
}
});
最后,当然是感谢我猪的独家技术支持啦~ ღ( ´・ᴗ・` )比心