1
1
import { asyncRouterHandle } from '@/utils/asyncRouter'
2
- import { emitter } from '@/utils/bus.js'
3
2
import { asyncMenu } from '@/api/menu'
4
3
import { defineStore } from 'pinia'
5
4
import { ref , watchEffect } from 'vue'
@@ -32,14 +31,14 @@ const formatRouter = (routes, routeMap, parent) => {
32
31
const KeepAliveFilter = ( routes ) => {
33
32
routes &&
34
33
routes . forEach ( ( item ) => {
35
- // 子菜单中有 keep-alive 的,父菜单也必须 keep-alive,否则无效。这里将子菜单中有 keep-alive 的父菜单也加入。
36
- if (
37
- ( item . children && item . children . some ( ( ch ) => ch . meta . keepAlive ) ) ||
38
- item . meta . keepAlive
39
- ) {
34
+ // 将所有需要 keep-alive 的组件直接抽层到最顶层 layout 下缓存
35
+ // 不再需要父菜单也加入 keep-alive,避免嵌套缓存问题
36
+ if ( item . meta . keepAlive ) {
40
37
const path = item . meta . path
41
- keepAliveRoutersArr . push ( pathInfo [ path ] )
42
- nameMap [ item . name ] = pathInfo [ path ]
38
+ if ( path && pathInfo [ path ] ) {
39
+ keepAliveRoutersArr . push ( pathInfo [ path ] )
40
+ nameMap [ item . name ] = pathInfo [ path ]
41
+ }
43
42
}
44
43
if ( item . children && item . children . length > 0 ) {
45
44
KeepAliveFilter ( item . children )
@@ -48,39 +47,13 @@ const KeepAliveFilter = (routes) => {
48
47
}
49
48
50
49
export const useRouterStore = defineStore ( 'router' , ( ) => {
51
- const keepAliveRouters = ref ( [ ] )
50
+ const keepAliveRouters = ref ( keepAliveRoutersArr )
51
+
52
52
const asyncRouterFlag = ref ( 0 )
53
- const setKeepAliveRouters = ( history ) => {
54
- const keepArrTemp = [ ]
55
-
56
- // 1. 首先添加原有的keepAlive配置
57
- keepArrTemp . push ( ...keepAliveRoutersArr )
58
-
59
- history . forEach ( ( item ) => {
60
- // 2. 为所有history中的路由强制启用keep-alive
61
- // 通过routeMap获取路由信息,然后通过pathInfo获取组件名
62
- const routeInfo = routeMap [ item . name ]
63
- if ( routeInfo && routeInfo . meta && routeInfo . meta . path ) {
64
- const componentName = pathInfo [ routeInfo . meta . path ]
65
- if ( componentName ) {
66
- keepArrTemp . push ( componentName )
67
- }
68
- }
69
-
70
- // 3. 如果子路由在tabs中打开,父路由也需要keepAlive
71
- if ( nameMap [ item . name ] ) {
72
- keepArrTemp . push ( nameMap [ item . name ] )
73
- }
74
- } )
75
-
76
- keepAliveRouters . value = Array . from ( new Set ( keepArrTemp ) )
77
- }
78
-
53
+
79
54
80
55
const route = useRoute ( )
81
56
82
- emitter . on ( 'setKeepAlive' , setKeepAliveRouters )
83
-
84
57
const asyncRouters = ref ( [ ] )
85
58
86
59
const topMenu = ref ( [ ] )
0 commit comments