keep-alive多级嵌套路由 发表于 2023-03-29 | 分类于 Components 123456789101112131415161718192021router.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) } } }} 12345678910111213141516171819202122 /** * 方法二:兼容<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) } } }}