keep-alive嵌套路由改造

105 阅读2分钟

路由注册不一定跟随菜单结构,不需要嵌套注册

1、项目描述

项目菜单结构如下

[{
  id:1,
  title:'一级菜单1',
  children:[
    {
      id:11,
      title:'二级菜单1',
      children:[{id:111,title:'三级菜单1'}]
    },{
      id:12,
      title:'二级菜单2',
      children:[{id:121,title:'三级菜单2'}]
    }
  ]
},{
  id:2,
  title:'一级菜单2',
  children:[
    {
      id:21,
      title:'二级菜单1',
      children:[{id:211,title:'三级菜单1'}]
    },{
       id:22,
       title:'二级菜单2',
      children:[{id:221,title:'三级菜单2'}]
    }
  ]
},{
   id:3,
   title:'一级菜单3',
}]

路由注册如下

import Vue from 'vue';
import VueRouter from 'vue-router';
 
Vue.use(VueRouter);
 
const routes = [
  {
    path: '/one',
    component: Content,
    redirect:{path:'/one/one/page11'},
    children:[
      {
          path: '/one/one',
          component: Content,
          redirect:{path:'/one/one/page11'},
          children:[{
              path: '/one/one/page11',
              component: Page11,
          }]
      },
      {
          path: '/one/two',
          component: Content,
          redirect:{path:'/one/two/page12'},
          children:[{
              path: '/one/two/page12',
              component: Page12,
          }]
      }
    ]
  },
  {
    path: '/two',
    component: Content,
    redirect:{path:'/two/one/page21'},
    children:[
      {
          path: '/two/one',
          component: Content,
          redirect:{path:'/two/one/page21'},
          children:[{
              path: '/two/one/page21',
              component: Page21,
          }]
      },
      {
          path: '/two/two',
          component: Content,
          redirect:{path:'/two/two/page22'},
          children:[{
              path: '/two/two/page22',
              component: Page22,
          }]
      }
    ]
  },
  {
    path: '/page3',
    component: Page3
  }
];
 
const router = new VueRouter({
  routes
});
 
new Vue({
  router
}).$mount('#app');

其中 Content.vue组件代码如下

<div class="content">
  <keep-alive :include="keepComponents">
      <router-view></router-view>
  <keep-alive>
</div>

2、问题描述

  • 添加:include里面需要包含当前页面所有层级的缓存,如缓存 path:'/two/one/page21',需要把 path:'/two'和path:'/two/one' 都缓存;如果已经打开同层 path:'/two/one/page22',则不用添加父级;
  • 删除:删除path:'/two/one/page21',需要删除 path:'/two'和path:'/two/one' ;如果已经打开同层 path:'/two/one/page22',则不用删除父级;

3、解决方案

  • 不使用嵌套路由,使用深度优先遍历,将路由打成只有一层
const routes = [
  {
      path: '/one/one/page11',
      component: Page11,
  },
  {
      path: '/one/two/page12',
      component: Page12,
  },
  {
     path: '/two/one/page21',
     component: Page21,
  },
  {
     path: '/two/two/page22',
     component: Page22,
  },
  {
    path: '/page3',
    component: Page3
  }
];
 

欢迎关注我的前端自检清单,我和你一起成长