Conditional keep-alive
You could provide methods for child routes to add/remove themselves to keep-alive's exclude property via a keepAliveExcludes reactive set. Expose the ref to the template as a computed array (the exclude prop requires Array, not Set):
// App.vue
import { provide, reactive, computed } from 'vue'
export default {
setup() {
const keepAliveExcludes = reactive(new Set())
provide('keepAliveExcludes', {
add: name => keepAliveExcludes.add(name),
remove: name => keepAliveExcludes.delete(name),
})
return {
keepAliveExcludes: computed(() => Array.from(keepAliveExcludes))
}
}
}
In the app template, bind keepAliveExcludes to <keep-alive>.exclude:
<template>
<router-view>
<keep-alive :exclude="keepAliveExcludes">
...
</keep-alive>
</router-view>
</template>
In the child route, inject the keepAliveExcludes, and call its add/remove with the component's name when needed (e.g., via checkbox):
<template>
<h1>About</h1>
<div>
<label>Keep Alive
<input type="checkbox" v-model="keepAlive">
</label>
</div>
</template>
<script>
import { ref, inject, watchEffect } from 'vue'
export default {
name: 'About',
setup() {
const { add: addKeepAliveExclude, remove: removeKeepAliveExclude } = inject('keepAliveExcludes', {})
const keepAlive = ref(true)
watchEffect(() => {
if (keepAlive.value) {
removeKeepAliveExclude?.('About')
} else {
addKeepAliveExclude?.('About')
}
})
return { keepAlive }
},
}
</script>
demo 1
Always exclude from keep-alive
If you need to always exclude the component from the keep-alive cache, you could simply set the component name statically without the complexity of the provide/inject above.
In the app template, specify the component's name (must match the name prop in the component declaration) in <keep-alive>.exclude:
<template>
<router-view>
<keep-alive exclude="About">
...
</keep-alive>
</router-view>
</template>
demo 2