vue中component is和keepAlive组合使用

component is用与动态渲染组件

组件基础 | Vue.js

<template>
    <div style="padding: 30px">
        <button @click="change('1')">组件1</button>
        <button @click="change('2')">组件2</button>
        <button @click="change('3')">组件3</button>
        <component :is="componentTag"></component>
    </div>
</template>
<script>
    import component1 from './component1'
    import component2 from './component2'
    import component3 from './component3'
    export default {
        components: {component1, component2, component3},
        data() {
            return {
                componentTag: '',
            }
        },
        methods: {
            change(index) {
                this.componentTag = 'component' + index
            },
        }
    }
</script>
<style scoped>
</style>

传给 :is 的值可以是以下几种:

  • 被注册的组件名
  • 导入的组件对象

也可以使用 is attribute 来创建一般的 HTML 元素。

当使用 <component :is="..."> 来在多个组件间作切换时,被切换掉的组件会被卸载。我们可以通过 <KeepAlive> 组件强制被切换掉的组件仍然保持“存活”的状态。

keepAlive用于缓存组件信息

<!-- 非活跃的组件将会被缓存! -->
<KeepAlive>
  <component :is="activeComponent" />
</KeepAlive>

在组件切换时状态也能被保留了

包含/排除

<KeepAlive> 默认会缓存内部的所有组件实例,但我们可以通过 include 和 exclude prop 来定制该行为。这两个 prop 的值都可以是一个以英文逗号分隔的字符串、一个正则表达式,或是包含这两种类型的一个数组

<!-- 以英文逗号分隔的字符串 -->
<KeepAlive include="a,b">
  <component :is="view" />
</KeepAlive>

<!-- 正则表达式 (需使用 `v-bind`) -->
<KeepAlive :include="/a|b/">
  <component :is="view" />
</KeepAlive>

<!-- 数组 (需使用 `v-bind`) -->
<KeepAlive :include="['a', 'b']">
  <component :is="view" />
</KeepAlive>

<script setup>
import Acomponet from "./a.vue"
import Bcomponet from "./b.vue"
import Ccomponet from "./C.vue"


</script>

<template>
<KeepAlive include='Acomponet,Bcomponet'>

<component :is="curCompoent">

</KeepAlive>


</temlate>

它会根据组件的 name 选项进行匹配,所以组件如果想要条件性地被 KeepAlive 缓存,就必须显式声明一个 name 选项。

TIP

在 3.2.34 或以上的版本中,使用 <script setup> 的单文件组件会自动根据文件名生成对应的 name 选项,无需再手动声明。

缓存实例的生命周期

当一个组件实例从 DOM 上移除但因为被 <KeepAlive> 缓存而仍作为组件树的一部分时,它将变为不活跃状态而不是被卸载。当一个组件实例作为缓存树的一部分插入到 DOM 中时,它将重新被激活

一个持续存在的组件可以通过 onActivated() 和 onDeactivated() 注册相应的两个状态的生命周期钩子:

  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值