<keep-alive>
是 Vue 内置组件,它可以将动态组件缓存起来,提高组件的渲染性能。
当一个组件被包裹在 <keep-alive>
标签中时,它的状态会被缓存,包括它的实例、生命周期钩子等。当组件被切换时,如果之前已经被渲染过,那么它就会直接从缓存中读取状态并渲染,而不是重新创建一个新的实例。
使用 <keep-alive>
需要注意以下几点:
<keep-alive>
只能用在动态组件或者用v-if
切换的组件上。- 被包裹的组件必须有一个独特的
key
属性,用于区分不同的缓存组件。 - 在缓存中的组件,不会被销毁和重新创建,因此也不会触发
created
和destroyed
生命周期钩子,但是activated
和deactivated
生命周期钩子会在组件被缓存和激活时触发。
下面是一个使用 <keep-alive>
的例子:
<template>
<div>
<button @click="toggle">Toggle</button>
<keep-alive>
<component :is="currentComponent" :key="currentComponent"></component>
</keep-alive>
</div>
</template>
<script>
export default {
data() {
return {
currentComponent: 'ComponentA'
}
},
methods: {
toggle() {
this.currentComponent = this.currentComponent === 'ComponentA' ? 'ComponentB' : 'ComponentA'
}
},
components: {
ComponentA: {
template: '<div>Component A</div>',
activated() {
console.log('Component A activated')
},
deactivated() {
console.log('Component A deactivated')
}
},
ComponentB: {
template: '<div>Component B</div>',
activated() {
console.log('Component B activated')
},
deactivated() {
console.log('Component B deactivated')
}
}
}
}
</script>
在上面的例子中,有两个组件 ComponentA
和 ComponentB
,它们会在点击按钮时相互切换。这两个组件都被包裹在 <keep-alive>
中,并且它们的 key
属性使用组件名来表示。当组件被缓存起来时,会触发对应组件的 activated
和 deactivated
生命周期钩子,我们可以在这两个钩子中打印日志来观察组件的激活和停用。