美文网首页前端开发那些事儿
keep-alive缓存路由在动态路径参数中出现的问题(二)

keep-alive缓存路由在动态路径参数中出现的问题(二)

作者: AaronZ_dd7f | 来源:发表于2020-08-15 11:55 被阅读0次

情景

  1. 使用ant-design-vue-pro基础上开发的项目
  2. 使用了multiTab
  3. 使用自定义layout,代码如下:
// @/layouts/FullPathKeepAlive.vue
<template>
  <keep-alive>
    <!-- 使用fullPath作为key,避免在keep-alive中,路由相同传,路径传参不同,却都共用一个vnode缓存 -->
    <router-view :key="$route.fullPath" />
  </keep-alive>
</template>

<script>
export default {
  name: 'FullPathKeepAlive'
}
</script>
  1. 编辑页面通过路径传参确定需要修改的数据,路径为/my-test/item/:id

问题

由于keep-alive缓存与MultiTab之前并不是联动的,固关闭单条数据的tab后,再次打开页面还是之前的状态。


关闭第一条编辑页的窗口后再次打开,并没有发生改变

解决思路

  1. 当前组件需要得到关闭tab的信息。
  2. 得到信息后清除对应的缓存
首先怎么让当前组件得到关闭tab的信息

ant-design-vue中MultiTab组件已经有封装好的eventBus,可以直接拿过来用

// @/components/MultiTab/events.js
import Vue from 'vue'
export default new Vue()

MultiTab组件中所有关闭标签最终都是调用的remove方法,在remove方法中自定义一个触发的事件remove-cache

// @/components/MultiTab/MultiTab.vue
import events from './events'
// ...
{
  // ...
  remove(targetKey) {
    // ...
    // 添加如下代码
    events.$emit('remove-cache', targetKey)
    // ...
  }
  // ...
}
// ...
清除对应的缓存
找到keep-alive组件的vue实例,发现和缓存有关的两个变量cache,keys keep-alive实例

翻vue源码src/core/components/keep-alive.js,证实这两个变量确实关系到缓存


src/core/components/keep-alive.js

那就将FullPathKeepAlive组件修改如下

<template>
  <keep-alive>
    <router-view :key="$route.fullPath" ref="page" />
  </keep-alive>
</template>

<script>
export default {
  name: 'FullPathKeepAlive',
  mounted () {
    // 监听消息
    this.$multiTab.instance.$on('remove-cache', (fullPath) => {
     // 清楚缓存
      const {
        cache, keys
      } = this.$refs.page.$vnode.parent.componentInstance
      if (cache[fullPath]) {
        delete cache[fullPath]
      }

      const index = keys.indexOf(fullPath)
      if (index > -1) {
        keys.splice(index, 1)
      }
    })
  }
}
</script>

相关文章

网友评论

    本文标题:keep-alive缓存路由在动态路径参数中出现的问题(二)

    本文链接:https://www.haomeiwen.com/subject/eflodktx.html