index.ts 2.31 KB
import { createRouter, createWebHistory, LocationQueryRaw } from 'vue-router';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css';

import usePermission from '@/hooks/permission';
import { clearToken, isLogin } from '@/utils/auth';
import PageLayout from '@/layout/index.vue';

import { useAuthorizedStore } from '@/store';
import appRoutes from './modules';

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/index.vue'),
      meta: {
        title: '登陆',
        requiresAuth: false,
      },
    },
    {
      name: 'root',
      path: '/',
      component: PageLayout,
      redirect: '/demos',
      children: appRoutes,
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'notFound',
      redirect: '/exception/404',
      meta: {
        requiresAuth: true,
      },
    },
  ],
  scrollBehavior() {
    return { top: 0 };
  },
});

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const authorizedStore = useAuthorizedStore();

  if (from.name !== undefined) {
    to.meta.from = from.name;
  }

  async function crossroads() {
    const Permission = usePermission();

    if (Permission.accessRouter(to)) {
      next();
    } else {
      next({ name: 'exception-403' });
    }
    NProgress.done();
  }

  if (isLogin()) {
    if (authorizedStore.permissions.length) {
      await crossroads();
    } else {
      try {
        await authorizedStore.syncInfo();
        await crossroads();
      } catch (error) {
        clearToken();
        next({ name: 'login', query: { path: to.path } as LocationQueryRaw });
        NProgress.done();
      }
    }
  } else {
    if (to.name === 'login') {
      next();
      NProgress.done();
      return;
    }

    if (to.name === 'root') {
      next({ name: 'login' });
    } else {
      next({ name: 'login', query: { path: to.path } as LocationQueryRaw });
    }
    NProgress.done();
  }
});

router.afterEach(async (to) => {
  sessionStorage.setItem(
    'route',
    to.meta?.breadcrumb?.toString() ||
      to.matched
        ?.slice(1)
        .map((item) => item.name)
        .toString() ||
      'dashboard'
  );
});

export default router;