有条件的keep-alive
您可以通过反应集provide
为子路由添加/删除自己keep-alive
的exclude
属性的方法。keepAliveExcludes
将 ref 作为计算数组公开给模板(exclude
prop 需要Array
,而不是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))
}
}
}
在应用模板中,绑定keepAliveExcludes
到<keep-alive>.exclude
:
<template>
<router-view>
<keep-alive :exclude="keepAliveExcludes">
...
</keep-alive>
</router-view>
</template>
在子路由中,inject
,keepAliveExcludes
并在需要时使用组件的名称调用它的add
/ remove
(例如,通过复选框):
<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>
演示 1
始终排除在keep-alive
如果您需要始终从keep-alive
缓存中排除组件,您可以简单地静态设置组件名称,而无需上述provide
/的复杂性inject
。
在 app 模板中,指定组件的名称(必须与name
组件声明中的 prop 匹配)<keep-alive>.exclude
:
<template>
<router-view>
<keep-alive exclude="About">
...
</keep-alive>
</router-view>
</template>
演示 2