keepAlive实现多级路由缓存

383 阅读1分钟

1、路由层级

Layout
     View
         Component
// 嵌套路由 Layout被渲染到最外层APP.vue中的<router-view>中,
// View 会被渲染到Layout的<router-view>内部, 
// Database会被渲染到View的<router-view>内部    
const metaDataRoute = {
  name: '元数据',// !!有时提示找不到路由 可能是name重复
  path: '/metaData',
  component: Layout,
  redirect: '/dataSource/database',
  children: [
    {
      name: '元数据',
      path: '/dataSource',
      component: View,
      icon: 'Coin',
      redirect: '/dataSource/database',
      children: [
        {
          name: '业务源数据库',
          path: '/dataSource/database',
          component: Database,
        },
        {
          name: '业务元数据管理',
          path: '/dataSource/metaData',
          component: MetaData,
        },
        {
          name: '数据同步列表',
          path: '/dataSource/syncList',
          component: SyncList,
          meta: {
            keepAlive: true
          }
        },
      ]
    },
  ]
};

三层路由 都要写
<router-view v-slot="{ Component }">
      <KeepAlive>
        <component :is="Component"/>
      </KeepAlive>
    </router-view>
需要缓存的路由
tabs中 
<router-view v-slot="{ Component }" >
          <KeepAlive :include="['Layout1', 'View1', 'SyncList']">
            <component :is="Component"  v-if="item.path == decodeURIComponent(route.fullPath)" :key="route.fullPath" />
          </KeepAlive>
          <component :is="Component" v-if="item.path == decodeURIComponent(route.fullPath)" :key="route.fullPath" />
      </router-view>
      

需要缓存的组件导出 name 和include中对应
export default {
  name: 'Layout1'
};

切换到已经打开的缓存页面时,这个组件的onMounted会再次执行,但是页面依然表单里的东西缓存了,这个可以把一些函数写在actived钩子函数里,但这样的方法不太好吧

而且会如果点击过缓存的页面,再点击不缓存页面,出现不缓存页面重复加载 所以最治标的方法是就把三级路由拍平成二级路由,菜单结构额外设置

2、三级路由keeepAlive总是出现问题,就把三级路由拍平成二级路由,菜单结构额外设置