vue3 内置组件keep-alive用法的全面介绍
基础用法
首先看一个反面例子
const app = Vue.createApp({
template: `
<button v-for="tab in tabs" @click="activeTab = tab" :style="activeTab === tab?{color: 'red'}:{}">{{ tab }}
</button>
<component :is="tabComponent"></component>`,
data() {
return {
tabs: ['A', 'B', 'C'],
activeTab: 'A'
}
},
computed: {
tabComponent() {
return 'Component' + this.activeTab
}
}
})
app.component('ComponentA', {
name: 'ComponentA',
template: `<div > component A </div>`
})
app.component('ComponentB', {
name: 'ComponentB',
template: `
<div>
<button @click="count--">-</button>
count: {{ count }}
<button @click="count++">+</button>
</div>`,
data() {
return {
count: 0
}
}
})
app.component('ComponentC', {
name: 'ComponentC',
template: `<div > component C </div>`
})
app.mount('#app')
如上图,当点击按钮切换到ComponentA
和ComponentC
再返回ComponentB
时,
count
的数值2不会被保存
如果将其中一段代码稍作修改
<component :is="tabComponent"></component>
<!--将上面的这个标签外部添加一个keep-alive标记-->
<keep-alive>
<component :is="tabComponent"></component>
</keep-alive>
无论怎么切换组件,count
的数值都会被保存
此外,keep-alive组件有三个属性:include
,exclude
和max
,下面介绍一下这三个参数的作用
组件属性include
和exclude
####include
- 属性作用:指定哪些组件
会
被缓存 - 属性类型:
string | RegExp | (string | RegExp)[]
,组件名,正则表达式或者数组
示例
<!--只有ComponentA和ComponentB两个组件会被缓存-->
<keep-alive :include="/Component[A,B]/">
<component :is="tabComponent"></component>
</keep-alive>
exclude
- 属性作用:指定哪些组件
不会
被缓存 - 属性类型:
string | RegExp | (string | RegExp)[]
,组件名,正则表达式或者数组
示例
<!--ComponentB和ComponentC两个组件不会被缓存-->
<keep-alive :exclude="/Component[B,C]/">
<component :is="tabComponent"></component>
</keep-alive>
组件属性max
可缓存的组件的最大数量。
如果max设置为2,当第三个页面需要被缓存时,缓存的第一个组件会被销毁
示例
<!--最多缓存两个组件-->
<keep-alive :max="2">
<component :is="tabComponent"></component>
</keep-alive>
生命周期钩子函数
当组件被缓存或者从缓存中重新激活,会分别触发生命周期的deactivated
和activated
两个钩子函数。
此外也会触发缓存组件下的子组件的这两个钩子函数