vue keepAlive 三级菜单缓存

发布时间 2023-03-23 16:38:30作者: 云里看海

需求:缓存跨二级三级菜单。
原来项目是二级路由,现在增加一个层级。这种情况菜单展示是没有问题的,只是新的三级菜单不能缓存。

1.搭建框架
2.使用keepAlive --include

<keep-alive :include="keepAliveList">
        <router-view :key="$route.path" />
</keep-alive>
 computed: {
    keepAliveList() {
      return this.$store.state.tagsView.keepAliveList
    },
    key() {
      return this.$route.path
    }
  },

3.新建三级routerview模板

 <router-view :key="$route.path" />

4.路由守卫拦截

router.beforeEach(async(to, from, next) => {
  /*三级菜单缓存*/
  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 === 'WayStation'){
        to.matched.splice(i, 1)
      }
    }
  }
  ...
})

心得:
routerview 使用keepalive include,不用v-if,可能会造成切换菜单触发内部已缓存页面的created请求。
数据类型使用array,提交页面或关闭将组件name从keepalive里面移除;进入时初始化keepalivelist