解决keep-alive无法缓存3级以上菜单

381 阅读1分钟

在vue-admin中,使用keep-alive缓存页面,当菜单为3级以上时会无法缓存,解决方法如下:

  1. 增加children-route-view包裹3级以上的路由
// children-route-view.vue

<template>
  <router-view />
</template>
<script>
export default {
  name: 'Blank'
}
</script>

2.修改路由component

import { RouteView, ChildrenRouteView } from '@/layouts'

export default [
  {
    path: '/first',
    name: 'First',
    component: RouteView,
    children: [
      {
        path: '/second',
        name: 'Second',
        component: ChildrenRouteView,
        children: [
          {
            path: '/third',
            name: 'Third',
            component: ChildrenRouteView,
            children: [
              {
                path: '/fourth',
                name: 'Fourth',
                component: () => import('@/views/A.vue')
              }
...
  1. 在路由守卫中控制菜单层级
router.beforeEach(async(to, from, next) => {
  // 解决keep-alive无法缓存3级以上菜单
  if (to.matched && to.matched.length > 2) {
    // 可能存在多个Blank,需循环删除
    const removeTimes = to.matched.filter(element => element?.components?.default?.name === 'Blank').length
    for (let i = 0; i < removeTimes; i++) {
      const index = to.matched.findIndex(element => element?.components?.default?.name === 'Blank')
      to.matched.splice(index, 1)
    }
  }
  ...
  1. 注意检查页面内的default name和路由的name是否一致
// @/views/A.vue

<template>
  ...
</template>
<script>
export default {
  name: 'Fourth'
}
</script>

写在最后: 查阅资料时有其他博主提出此方法可能导致面包屑出现层级问题,因为我的项目里没有使用面包屑,所以有使用的jym慎用此方法