index.ts 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { createRouter, createWebHashHistory } from "vue-router"
  2. import { constRoutes, asyncComponents } from "./routers"
  3. import NProgress from "@/plugin/nprogress"
  4. import { ElMessage } from "element-plus"
  5. import { getToken, CODE401 } from "@/libs/auth"
  6. import { generateAsyncMenusAsyncRoutes } from "@/libs/utils"
  7. import userStore from "@/store/modules/user"
  8. import { closeAllModalFrame } from "@/plugin/modalFrame"
  9. const userStoreHook = userStore()
  10. const router = createRouter({
  11. history: createWebHashHistory(process.env.BASE_URL),
  12. routes: constRoutes,
  13. scrollBehavior() {
  14. return { left: 0, top: 0 }
  15. }
  16. })
  17. function isRegWhite(regs: RegExp[], path: string) {
  18. return (
  19. regs.findIndex(reg => {
  20. return reg.test(path)
  21. }) > -1
  22. )
  23. }
  24. const authWhiteList = ["/login"] // 不访问接口权限白名单
  25. const regWhiteList: RegExp[] = [] //正则白名单(用于系统不需要权限的分享页面)
  26. //存储动态添加的需要删除的路由
  27. let removeRoutes: (() => void)[] = []
  28. router.beforeEach((to, from, next) => {
  29. NProgress.start()
  30. const hasToken = getToken()
  31. //如果有token且不是白名单页面则加载info
  32. if (hasToken && !authWhiteList.includes(to.path)) {
  33. //有roles时候
  34. const hasRoles = userStoreHook.roles
  35. if (hasRoles) {
  36. next()
  37. } else {
  38. userStoreHook
  39. .getUserInfo()
  40. .then(menus => {
  41. const { asyncRoutes } = generateAsyncMenusAsyncRoutes(menus, asyncComponents) //获取动态路由和菜单
  42. //新增路由并保存 删除路由方法
  43. asyncRoutes.map(asyncRoute => {
  44. removeRoutes.push(router.addRoute(asyncRoute))
  45. })
  46. next({ ...to, replace: true }) //防止addRoutes没有加载完 就跳转
  47. })
  48. .catch((err: apiResDataType) => {
  49. //退出 清空,当是登录权限问题时候 axios 里面会清空
  50. if (err.code !== CODE401) {
  51. ElMessage.error(err.message)
  52. userStoreHook.resetUser()
  53. }
  54. })
  55. }
  56. } else {
  57. // 如果有token,并且是登录页 直接返回首页
  58. if (hasToken && to.path === "/login") {
  59. next({
  60. path: "/"
  61. })
  62. return
  63. }
  64. if (authWhiteList.includes(to.path) || isRegWhite(regWhiteList, to.path)) {
  65. next()
  66. } else {
  67. next({
  68. path: "/login"
  69. })
  70. }
  71. }
  72. })
  73. router.afterEach(() => {
  74. closeAllModalFrame()
  75. NProgress.done()
  76. })
  77. /** 重置router */
  78. export const resetRouter = () => {
  79. //清空动态添加的路由
  80. removeRoutes.map(removeRoute => {
  81. removeRoute()
  82. })
  83. removeRoutes = []
  84. }
  85. export default router