---
title: "解决vue使用keep-alive三级页面缓存问题"
author: "xiaotongeye"
date: "2021-08-31T18:24:10Z"
tags: []
categories: ["Web前端"]
slug: "vue-keep-alive"
draft: false
lastmod: "2021-08-31T18:27:19Z"
id: 2520885
url: "https://xiaotongeye.iteye.com/blog/2520885"
---

**需求描述：**管理后台存在三级页面，列表页和详情页，列表页缓存，详情页不缓存

**实现：**使用keep-alive的include，两级页面都需要添加keep-alive，借鉴[vue-element-admin](https://panjiachen.github.io/vue-element-admin-site/zh/) tags-view组件的visitedViews状态对缓存页面进行管理

```
// home.vue
<keep-alive :include="cachedViews">
    <router-view :key="key"></router-view>
</keep-alive>

computed: {
      key() {
        return this.$route.fullPath
      },
      cachedViews() {
        return this.$store.state.tagsView.cachedViews
      },
},
```

 

```
// 二级页面
<keep-alive>
      <router-view></router-view>
</keep-alive>
```

 

```
// 全局钩子
beforeRouteEnter(to, from, next) {
    // 解决三级菜单缓存问题
    if (to.matched&&to.matched.length > 2) {
      for(let i = 1; i < to.matched.length; i ++) {
        const element = to.matched[i]
        if (pageArr.includes(element.components.default.name)) {
          to.matched.splice(i, 1)
        }
      }
    }
    next()
}
```