diff --git a/src/permission.ts b/src/permission.ts index 669d1a24..abe4310a 100644 --- a/src/permission.ts +++ b/src/permission.ts @@ -1,5 +1,5 @@ import router from '@/router'; -import { RouteRecordRaw } from 'vue-router'; +import { getToken } from '@/utils/auth'; import { useUserStoreHook } from '@/store/modules/user'; import { usePermissionStoreHook } from '@/store/modules/permission'; @@ -15,25 +15,26 @@ const whiteList = ['/login']; router.beforeEach(async (to, from, next) => { NProgress.start(); const userStore = useUserStoreHook(); - if (userStore.token) { - // 登录成功,跳转到首页 + + const hasToken = getToken(); + if (hasToken) { if (to.path === '/login') { + // if is logged in, redirect to the home page next({ path: '/' }); - NProgress.done(); } else { - const hasGetUserInfo = userStore.roles.length > 0; - if (hasGetUserInfo) { + const hasRoles = userStore.roles && userStore.roles.length > 0; + if (hasRoles) { + // 路由未匹配,跳转404 if (to.matched.length === 0) { - from.name ? next({ name: from.name as any }) : next('/401'); + from.name ? next({ name: from.name }) : next('/404'); } else { next(); } } else { try { const { roles } = await userStore.getInfo(); - const accessRoutes: RouteRecordRaw[] = - await permissionStore.generateRoutes(roles); - accessRoutes.forEach((route: any) => { + const accessRoutes = await permissionStore.generateRoutes(roles); + accessRoutes.forEach(route => { router.addRoute(route); }); next({ ...to, replace: true }); diff --git a/src/router/index.ts b/src/router/index.ts index 7e9e487f..37cd2cfa 100644 --- a/src/router/index.ts +++ b/src/router/index.ts @@ -16,16 +16,12 @@ export const constantRoutes: RouteRecordRaw[] = [ } ] }, + { path: '/login', component: () => import('@/views/login/index.vue'), meta: { hidden: true } }, - { - path: '/404', - component: () => import('@/views/error-page/404.vue'), - meta: { hidden: true } - }, { path: '/', @@ -44,7 +40,12 @@ export const constantRoutes: RouteRecordRaw[] = [ meta: { hidden: true } }, { - path: 'apidoc', + path: '/404', + component: () => import('@/views/error-page/404.vue'), + meta: { hidden: true } + }, + { + path: '/apidoc', component: () => import('@/views/demo/apidoc.vue'), meta: { hidden: true } } @@ -104,7 +105,9 @@ export const constantRoutes: RouteRecordRaw[] = [ }*/ ]; -// 创建路由 +/** + * 创建路由 + */ const router = createRouter({ history: createWebHashHistory(), routes: constantRoutes as RouteRecordRaw[], @@ -112,15 +115,12 @@ const router = createRouter({ scrollBehavior: () => ({ left: 0, top: 0 }) }); -// 重置路由 +/** + * 重置路由 + */ export function resetRouter() { - const permissionStore = usePermissionStoreHook(); - permissionStore.routes.forEach(route => { - const name = route.name; - if (name && router.hasRoute(name)) { - router.removeRoute(name); - } - }); + router.replace({ path: '/login' }); + location.reload(); } export default router;