Vue 系统组件 <KeepAlive> 简介

<KeepAlive> 缓存组件 

注意:只支持H5端

<KeepAlive include = "" exclude = "" max = ""></KeepAlive>

 @说明:缓存被包裹的组件

先看段动态绑定组件代码:

<component :is="activeComponent"></component>

在上例代码中,随着组件的动态切换,旧的组件会被删除新的组件会被新建

这样带来一个问题,比如旧组件是一个表单,上面有我之前选择选项及录入的内容。如果我切回旧组件时,之前的录入将丢失

所以<KeepAlive>组件能解决这个问题,它会在切换组件时,缓存旧组件。代码如下:

<KeepAlive>
    <component :is="activeComponent"></component>
</KeepAlive>

 

 

 

一、当一个组件在 <KeepAlive> 中被切换时,它的 activateddeactivated 生命周期钩子将被调用

 

二、<KeepAlive> 组件属性:

<KeepAlive include = "" exclude = "" max = ""></KeepAlive>

 

 include 属性:

@说明:  [可选] 默认会缓存内部的所有组件实例,include可以指定要缓存的组件

用法一:用逗号分隔的字符串

<!-- 指定组件a,b被缓存 -->
<KeepAlive include="a,b">
  <component :is="view"></component>
</KeepAlive>

 

用法二:正则表达式

<!-- 指明组件 a和b被缓存 -->
<KeepAlive :include="/a|b/">
  <component :is="view"></component>
</KeepAlive>

 

用法三:数组

<!-- 指明组件 a和b被缓存 -->
<KeepAlive :include="['a', 'b']">
  <component :is="view"></component>
</KeepAlive>

 

 

exclude 属性:

@说明:  [可选] 指定的组件不会被缓存,它用法和include相同

 

 

max属性:

@说明: [可选] 最大缓存实例数

<KeepAlive :max="10">
  <component :is="view"></component>
</KeepAlive>

  

 

示例:

组件 ComTestA.vue

<template>
    <view>
        <h3>本人信息<small>(已输入的表单数据会被缓存)</small></h3>
        <uni-easyinput
            placeholder="您的姓名"
            inputBorder
        >
        </uni-easyinput>
        <uni-data-checkbox :localdata="sexConfig"> </uni-data-checkbox>
    </view>
</template>

<script setup>
    const sexConfig = [{
        "value": 0,
        "text": ""
    }, {
        "value": 1,
        "text": ""
    }]
</script>

 

 

组件 ComTestB.vue

<template>
    <view>
        <h3>配偶信息<small>(已输入的表单数据不会被缓存)</small></h3>
        <uni-easyinput
            placeholder="配偶姓名"
            inputBorder
        >
        </uni-easyinput>
        <uni-data-checkbox :localdata="sexConfig"> </uni-data-checkbox>
    </view>
</template>

<script setup>
    const sexConfig = [{
        "value": 0,
        "text": ""
    }, {
        "value": 1,
        "text": ""
    }]
</script>

 

演示页面:

<template>
    <uni-data-checkbox v-model="formType" :localdata="formData"> </uni-data-checkbox>
    <KeepAlive include="ComTestA">
<!-- 这里必需要调用函数方式,直接componentName无法执行 -->
<component :is="componentName()"></component> </KeepAlive> </template> <script setup> import { ref } from 'vue' // uni-app 中动态组件必需要引入 import ComTestA from '@/components/ComTestA/ComTestA.vue' import ComTestB from '@/components/ComTestB/ComTestB.vue' const formData = [{ "value": 0, "text": "个人信息" }, { "value": 1, "text": "配偶信息" }] const formType = ref(0) var componentName = () => { return !formType.value ? ComTestA : ComTestB } </script>

 

posted @ 2022-09-19 14:25  1024记忆  阅读(270)  评论(0编辑  收藏  举报