refactor: 路由多级缓存调整为扁平化方案

This commit is contained in:
2024-05-04 21:45:12 +08:00
parent 308938a0f6
commit 5f3dd93376
5 changed files with 55 additions and 36 deletions

View File

@@ -1,13 +1,15 @@
import { ref, toRaw } from 'vue'
import { ref } from 'vue'
import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'
import { constantRoutes } from '@/router'
import Layout from '@/layout/index.vue'
import ParentView from '@/components/ParentView/index.vue'
import { getUserRoute, type RouteItem } from '@/apis'
import { mapTree } from 'xe-utils'
import { mapTree, toTreeArray } from 'xe-utils'
import { cloneDeep, omit } from 'lodash-es'
import { transformPathToName } from '@/utils'
const Layout = () => import('@/layout/index.vue')
// 匹配views里面所有的.vue文件
const modules = import.meta.glob('@/views/**/*.vue')
@@ -64,6 +66,28 @@ const formatAsyncRoutes = (menus: RouteItem[]) => {
return routes as RouteRecordRaw[]
}
/** 判断路由层级是否大于 2 */
export const isMultipleRoute = (route: RouteRecordRaw) => {
const children = route.children
if (children?.length) {
// 只要有一个子路由的 children 长度大于 0就说明是三级及其以上路由
return children.some((child) => child.children?.length)
}
return false
}
/** 路由降级(把三级及其以上的路由转化为二级路由) */
export const flatMultiLevelRoutes = (routes: RouteRecordRaw[]) => {
const cloneRoutes = cloneDeep(routes)
cloneRoutes.forEach((route) => {
if (isMultipleRoute(route)) {
const flatRoutes = toTreeArray(route.children)
route.children = flatRoutes.map((i) => omit(i, 'children')) as RouteRecordRaw[]
}
})
return cloneRoutes
}
const storeSetup = () => {
// 所有路由(常驻路由 + 动态路由)
const routes = ref<RouteRecordRaw[]>([])
@@ -74,7 +98,6 @@ const storeSetup = () => {
const setRoutes = (data: RouteRecordRaw[]) => {
routes.value = constantRoutes.concat(data)
asyncRoutes.value = data
console.log('路由', toRaw(routes.value))
}
// 生成路由
@@ -84,7 +107,9 @@ const storeSetup = () => {
getUserRoute().then((res) => {
const asyncRoutes = formatAsyncRoutes(res.data)
setRoutes(asyncRoutes)
resolve(asyncRoutes)
const cloneRoutes = cloneDeep(asyncRoutes)
const flatRoutes = flatMultiLevelRoutes(cloneRoutes as RouteRecordRaw[])
resolve(flatRoutes)
})
})
}

View File

@@ -10,7 +10,8 @@ const storeSetup = () => {
const cacheList = ref<RouteRecordName[]>([]) // keep-alive缓存的数组, 元素是组件名
// 添加一个页签, 如果当前路由已经打开, 则不再重复添加
const addTagItem = (item: RouteRecordRaw) => {
const addTagItem = (route: RouteRecordRaw) => {
const item = JSON.parse(JSON.stringify(route))
if (tagList.value.some((i) => i.path === item.path)) return
if (item.meta?.showInTabs ?? true) {
tagList.value.push(item)
@@ -35,7 +36,7 @@ const storeSetup = () => {
const arr: RouteRecordRaw[] = []
_XEUtils_.eachTree(routeStore.routes, (item) => {
if (item.meta?.affix ?? false) {
arr.push(item)
arr.push(JSON.parse(JSON.stringify(item)))
}
})
tagList.value = arr