12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- import { createRouter, createWebHashHistory } from "vue-router"
- import { constRoutes, asyncComponents } from "./routers"
- import NProgress from "@/plugin/nprogress"
- import { ElMessage } from "element-plus"
- import { getToken, CODE401 } from "@/libs/auth"
- import { generateAsyncMenusAsyncRoutes } from "@/libs/utils"
- import userStore from "@/store/modules/user"
- import { closeAllModalFrame } from "@/plugin/modalFrame"
- const userStoreHook = userStore()
- const router = createRouter({
- history: createWebHashHistory(process.env.BASE_URL),
- routes: constRoutes,
- scrollBehavior() {
- return { left: 0, top: 0 }
- }
- })
- function isRegWhite(regs: RegExp[], path: string) {
- return (
- regs.findIndex(reg => {
- return reg.test(path)
- }) > -1
- )
- }
- const authWhiteList = ["/login"] // 不访问接口权限白名单
- const regWhiteList: RegExp[] = [] //正则白名单(用于系统不需要权限的分享页面)
- //存储动态添加的需要删除的路由
- let removeRoutes: (() => void)[] = []
- router.beforeEach((to, from, next) => {
- NProgress.start()
- const hasToken = getToken()
- //如果有token且不是白名单页面则加载info
- if (hasToken && !authWhiteList.includes(to.path)) {
- //有roles时候
- const hasRoles = userStoreHook.roles
- if (hasRoles) {
- next()
- } else {
- userStoreHook
- .getUserInfo()
- .then(menus => {
- const { asyncRoutes } = generateAsyncMenusAsyncRoutes(menus, asyncComponents) //获取动态路由和菜单
- //新增路由并保存 删除路由方法
- asyncRoutes.map(asyncRoute => {
- removeRoutes.push(router.addRoute(asyncRoute))
- })
- next({ ...to, replace: true }) //防止addRoutes没有加载完 就跳转
- })
- .catch((err: apiResDataType) => {
- //退出 清空,当是登录权限问题时候 axios 里面会清空
- if (err.code !== CODE401) {
- ElMessage.error(err.message)
- userStoreHook.resetUser()
- }
- })
- }
- } else {
- // 如果有token,并且是登录页 直接返回首页
- if (hasToken && to.path === "/login") {
- next({
- path: "/"
- })
- return
- }
- if (authWhiteList.includes(to.path) || isRegWhite(regWhiteList, to.path)) {
- next()
- } else {
- next({
- path: "/login"
- })
- }
- }
- })
- router.afterEach(() => {
- closeAllModalFrame()
- NProgress.done()
- })
- /** 重置router */
- export const resetRouter = () => {
- //清空动态添加的路由
- removeRoutes.map(removeRoute => {
- removeRoute()
- })
- removeRoutes = []
- }
- export default router
|