Subscribe on changes!

Removing one route instance from keep-alive also destroys other instances sharing the same component

avatar
Mar 30th 2023

Vue version

3.2.47

Link to minimal reproduction

Steps to reproduce

1.Create two routes with the same component name and cache their instances using the keep-alive component.

const routes = [
  { path: '/page1', name: 'Test', component: Test, meta: { keepAlive: true }},
  { path: '/page2', name: 'Test', component: Test, meta: { keepAlive: true }}
]

2.Add an onUnmounted hook to the Test component to log when the component is destroyed.

Test.vue:

import { onUnmounted } from 'vue'

export default {
  name: 'Test',
  setup() {
    onUnmounted(() => {
      console.log('Component destroyed')
    })
  }
}

3.Entering the /page1 and /page2 routes, you can see that the Test component is cached. 4.Closing one of these routes will see that all cached Test components are destroyed and logged to the console.

What is expected?

Only the cached component corresponding to the closed route will be destroyed; other cached components should not be affected.

What is actually happening?

All cached components that share the same component name are destroyed.

System Info

System:
    OS: Windows 10 10.0.17763
    CPU: (8) x64 Intel(R) Core(TM) i7-10510U CPU @ 1.80GHz
    Memory: 7.77 GB / 15.60 GB
  Binaries:
    Node: 18.12.1 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.19 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
    npm: 8.19.2 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Google Chrome Explorer: 111.0.5563.147

Any additional comments?

This behavior seems to be due to the fact that keep-alive only caches components based on their name, and not based on the route path or any other identifier. As a result, all instances that share the same component name are considered equivalent, and removing one of them from the cache causes all of them to be destroyed.

After further testing, it was found that in Vue.js version 2.x, when using the same component name to cache different routing instances, removing one of the routing instances only destroys the caching component corresponding to that routing instance, and the other caching components are not affected. Therefore, this issue may be a bug in Vue.js 3.x.

Related Links one

Related Links two

avatar
Mar 30th 2023

Could you provide a runnable minimal reproduction?

avatar
May 10th 2023

https://www.cnblogs.com/shanfeng1000/p/16692266.html https://www.cnblogs.com/shanfeng1000/p/16708878.html 我也遇到这个问题, 这里找到了一些方案, 但是觉得不够好, 如果 vue 可以把 KeepAlive 的 pruneCacheEntry 方法 expose 出来, 这些问题就迎刃而解了

avatar
Sep 14th 2023

+1

avatar
Sep 17th 2023

Closing due to inactivity. Please open a new issue with a reference to this one if you can follow up with more information.