keep-alive多级嵌套路由

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
router.beforeEach((to, from, next) => {
...
handleKeepAlive(to)
...
}
/**
* 递归处理多余的 layout : <router-view>,
* 让需要访问的组件保持在第一层 index : <router-view> 之下
* @param to
*/
function handleKeepAlive (to) {
if (to.matched && to.matched.length > 2) {
for (let i = 0; i < to.matched.length; i++) {
const element = to.matched[i]
if (element.components.default.name === 'layout') {
to.matched.splice(i, 1)
handleKeepAlive(to)
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    
/**
* 方法二:兼容<layout>按需加载
* @param to
*/
async function handleKeepAlive (to) {
if (to.matched && to.matched.length > 2) {
for (let i = 0; i < to.matched.length; i++) {
const element = to.matched[i]
if (element.components.default.name === 'layout') {
to.matched.splice(i, 1)
await handleKeepAlive(to)
}
// 如果没有按需加载完成则等待加载
if (typeof element.components.default === 'function') {
await element.components.default()
await handleKeepAlive(to)
}
}
}
}