Check out the fantastic response from @tony19, although it seems to be encountering some issues due to a potential bug in VUE (I'm currently using version 3.2.6).
The problem arises when a component is excluded from being kept alive after it's initiated, and then the maximum number of keep-alive components is reached. VUE attempts to remove the non-existent excluded component, causing an error that halts the application. More details on this error can be found below.
To resolve this issue, I decided to build upon Tony19's excellent solution. Instead of excluding the component after it has loaded, I set up rules in the router just before loading the component.
const routes = [
/* ... */
{
path: "/about",
name: "AboutPage",
meta: { excludeKeepAlive: true },
component: () => import('./../components/AboutPage.vue'),
}
/* ... */
];
Here is how this approach was implemented in the main APP:
/* Main app logic goes here */
export default {
setup() {
/* ... */
const keepAliveExcludes = reactive(new Set());
cont keepAliveExcluder= {
add: name => keepAliveExcludes.add(name),
remove: name => keepAliveExcludes.delete(name),
}
router.beforeEach((to, from, next) => {
if(to.meta?.excludeKeepAlive===true){
keepAliveExcluder.add(to.name);
}
next();
});
/* ... */
return {
keepAliveExcludes: computed(() => Array.from(keepAliveExcludes))
}
}
}
Further details on the error (potentially a bug)
The error is triggered at line 2057 of runtime-core.esm-bundler.js
Uncaught (in promise) TypeError: Cannot read property 'type' of undefined
This error occurs because VUE is unable to locate the dynamically excluded component.
https://i.sstatic.net/4e7SN.png