vue3 内置组件keep-alive用法的全面介绍

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')

在这里插入图片描述

如上图,当点击按钮切换到ComponentAComponentC再返回ComponentB时,
count的数值2不会被保存

如果将其中一段代码稍作修改

<component :is="tabComponent"></component>
<!--将上面的这个标签外部添加一个keep-alive标记-->
<keep-alive>
    <component :is="tabComponent"></component>
</keep-alive>

无论怎么切换组件,count的数值都会被保存

此外,keep-alive组件有三个属性:include,excludemax,下面介绍一下这三个参数的作用

组件属性includeexclude

####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>

生命周期钩子函数

当组件被缓存或者从缓存中重新激活,会分别触发生命周期的deactivatedactivated两个钩子函数。

此外也会触发缓存组件下的子组件的这两个钩子函数

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bdawn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值