是 Vue 内置的一个抽象组件,可以将其包裹的动态组件进行缓存,以避免多次重渲染,从而提高应用的性能。
使用方式:
<keep-alive>
<component :is="currentComponent"></component>
</keep-alive>
当 currentComponent 改变时, 会根据其 key 属性的值来决定是否缓存当前组件实例。如果 key 相同,则使用缓存的组件实例,否则销毁旧实例,重新创建新实例。
下面是 的一些常用属性:
include: 字符串或正则表达式,只有匹配的组件会被缓存。
exclude: 字符串或正则表达式,不匹配的组件会被缓存。
max: 数字,指定缓存的最大组件数,超出则会按照 LRU 策略进行清除。
需要注意的是,由于缓存的组件实例会保留其状态,因此需要在使用缓存组件时注意对其状态的管理,以避免状态污染。
以下是一个示例,演示如何使用 来缓存组件:
<template>
<div>
<button @click="toggle">Toggle Component</button>
<keep-alive>
<component :is="currentComponent"></component>
</keep-alive>
</div>
</template>
<script>
export default {
data() {
return {
currentComponent: 'A',
components: ['A', 'B', 'C']
}
},
methods: {
toggle() {
const currentIndex = this.components.indexOf(this.currentComponent)
this.currentComponent = this.components[(currentIndex + 1) % this.components.length]
}
}
}
</script>
在这个示例中,我们使用一个按钮来切换三个不同的组件。由于使用了 ,每个组件只会被创建一次,当切换回已缓存的组件时,它的状态将被恢复。