import { createRouter, createWebHashHistory } from 'vue-router' import type { RouteRecordRaw } from 'vue-router' import { useNProgress } from '@vueuse/integrations/useNProgress' // import useMenuStore from '@/store/modules/menu' import '@/assets/styles/nprogress.scss' // 路由相关数据 import { asyncRoutes, constantRoutes, systemRoutes } from './routes' import useSettingsStore from '@/store/modules/settings' import useKeepAliveStore from '@/store/modules/keepAlive' // import useRouteStore from '@/store/modules/route' const { isLoading } = useNProgress() // const menuStore = useMenuStore() // const routeStore = useRouteStore() const router = createRouter({ history: createWebHashHistory(), routes: [...asyncRoutes, ...systemRoutes, ...constantRoutes] as RouteRecordRaw[], }) router.beforeEach(async (to, from, next) => { console.log('to:', to.path) isLoading.value = true next() }) router.afterEach((to, from) => { const settingsStore = useSettingsStore() const keepAliveStore = useKeepAliveStore() isLoading.value = false // 设置页面 title to.meta.title && settingsStore.setTitle(typeof to.meta.title === 'function' ? to.meta.title() : to.meta.title) // 判断当前页面是否开启缓存,如果开启,则将当前页面的 name 信息存入 keep-alive 全局状态 if (to.meta.cache) { const componentName = to.matched[to.matched.length - 1].components?.default.name // debugger if (componentName) { keepAliveStore.add(componentName) } else { console.warn('该页面组件未设置组件名,会导致缓存失效,请检查') } } // 判断离开页面是否开启缓存,如果开启,则根据缓存规则判断是否需要清空 keep-alive 全局状态里离开页面的 name 信息 if (from.meta.cache) { const componentName = from.matched[to.matched.length - 1].components?.default.name if (componentName) { // 通过 meta.cache 判断针对哪些页面进行缓存 switch (typeof from.meta.cache) { case 'string': if (from.meta.cache !== to.name) { keepAliveStore.remove(componentName) } break case 'object': if (!from.meta.cache.includes(to.name as string)) { keepAliveStore.remove(componentName) } break } // 如果进入的是 reload 页面,则也将离开页面的缓存清空 if (to.name === 'reload') { keepAliveStore.remove(componentName) } } } document.documentElement.scrollTop = 0 }) export default router