import Vue from 'vue' import VueRouter, { RouteConfig, Route } from 'vue-router' import HomeView from '../views/HomeView.vue' const { SYSTEM_APP_NAME, SYSTEM_PRO_PUBLIC_PATH, SYSTEM_ACTIVE_RULE, SYSTEM_DEV_PORT, SYSTEM_DEV_PUBLIC_PATH, // eslint-disable-next-line @typescript-eslint/no-var-requires } = require('../../../../micro/config') import { getToken } from '@/util/auth' import { useLoadingStore } from '@/store/loading' import pinia from '@/store' import { useUserStore } from '@/store/user' import { useAppStore } from '@/store/app' Vue.use(VueRouter) interface IMeta { title?: string // 标题 backgroundColor?: string dismiss?: boolean middleware?: string // 要运行的中间件名称,多个中间件使用 ',' 进行拼接,例如 '中间件A,中间件B,中间件C' keepAlive?: boolean // 路由页面是要需要 keepAlive 特性 redirect?: string // 页面是否要重定向至某一个页面 } const originalPush = VueRouter.prototype.push //push // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore VueRouter.prototype.push = function push(location, onResolve, onReject) { if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject) // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore return originalPush.call(this, location).catch((err) => err) } const routes: Array = [ { path: '/', name: 'home', component: HomeView, redirect: '/system', }, { path: '/login', component: () => import('@/views/MicroApp.vue'), meta: { appName: SYSTEM_APP_NAME, activeRule: SYSTEM_ACTIVE_RULE, proPublicPath: SYSTEM_PRO_PUBLIC_PATH, devPublicPath: SYSTEM_DEV_PUBLIC_PATH, devPort: SYSTEM_DEV_PORT, }, }, ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes, }) const loadingStore = useLoadingStore(pinia) const userStore = useUserStore(pinia) const appStore = useAppStore(pinia) router.beforeEach(async (to: Route, from: Route, next) => { loadingStore.start() next() }) router.beforeResolve(async (to: Route, from: Route, next) => { const accessToken1 = getToken() const toMeta: IMeta = to.meta || {} if (toMeta.dismiss !== true) { if (!accessToken1 || accessToken1.length < 32) { if (to.path === '/login') { next() } else { next({ path: '/login', query: { redirect: to.path } }) } return } else { return userStore .logged(accessToken1) .then(() => { next() }) .catch((err) => { // eslint-disable-next-line no-console console.log(err) next({ path: '/login', query: { redirect: to.path } }) }) } } next() }) router.afterEach((to) => { const toMeta: IMeta = to.meta || {} // 设置背景色 appStore.setBgColor(toMeta.backgroundColor) // 设置标题 appStore.changeTitle(toMeta.title) // 设置loading状态为已完成 loadingStore.completed() }) export default router