@@ -3,6 +3,7 @@ import { asyncRouterHandle } from '@/utils/asyncRouter'
33import { asyncMenu } from '@/api/menu'
44
55const routerList = [ ]
6+ const keepAliveRouters = [ ]
67
78const formatRouter = ( routes ) => {
89 routes && routes . forEach ( item => {
@@ -16,11 +17,24 @@ const formatRouter = (routes) => {
1617 } )
1718}
1819
20+ const KeepAliveFilter = ( routes ) => {
21+ routes && routes . forEach ( item => {
22+ // 子菜单中有 keep-alive 的,父菜单也必须 keep-alive,否则无效。这里将子菜单中有 keep-alive 的父菜单也加入。
23+ if ( ( item . children && item . children . some ( ch => ch . meta . keepAlive ) || item . meta . keepAlive ) ) {
24+ item . component ( ) . then ( val => { keepAliveRouters . push ( val . default . name ) } )
25+ }
26+ if ( item . children && item . children . length > 0 ) {
27+ KeepAliveFilter ( item . children )
28+ }
29+ } )
30+ }
31+
1932export const router = {
2033 namespaced : true ,
2134 state : {
2235 asyncRouters : [ ] ,
2336 routerList : routerList ,
37+ keepAliveRouters : keepAliveRouters
2438 } ,
2539 mutations : {
2640 setRouterList ( state , routerList ) {
@@ -29,6 +43,10 @@ export const router = {
2943 // 设置动态路由
3044 setAsyncRouter ( state , asyncRouters ) {
3145 state . asyncRouters = asyncRouters
46+ } ,
47+ // 设置需要缓存的路由
48+ setKeepAliveRouters ( state , keepAliveRouters ) {
49+ state . keepAliveRouters = keepAliveRouters
3250 }
3351 } ,
3452 actions : {
@@ -62,8 +80,10 @@ export const router = {
6280
6381 } )
6482 asyncRouterHandle ( baseRouter )
83+ KeepAliveFilter ( asyncRouter )
6584 commit ( 'setAsyncRouter' , baseRouter )
6685 commit ( 'setRouterList' , routerList )
86+ commit ( 'setKeepAliveRouters' , keepAliveRouters )
6787 return true
6888 }
6989 } ,
@@ -74,6 +94,9 @@ export const router = {
7494 } ,
7595 routerList ( state ) {
7696 return state . routerList
97+ } ,
98+ keepAliveRouters ( state ) {
99+ return state . keepAliveRouters
77100 }
78101 }
79102}
0 commit comments