Vue:内置组件:KeepAlive(缓存组件实例)

一、作用

<KeepAlive></KeepAlive>能缓存包裹的所有组件,保证组件在切换时维持组件状态。

默认情况下,一个组件实例在被替换掉后会被销毁。这会导致它丢失其中所有已变化的状态------当这个组件再一次被显示时,会创建一个只带有初始状态的新实例。KeepAlive能让组件缓存,保留它的状态。

二、效果展示

组件A:

html 复制代码
<template>
  <div class="page">
    {{ a }}
    <button @click="a++">+1</button>
  </div>
</template>
<script setup lang="ts">
import { ref } from "vue";
const a = ref(1);
</script>

组件B:

html 复制代码
<template>
  <div class="page">这里是组件B</div>
</template>

页面,未使用KeepAlive:

html 复制代码
<template>
  <div class="page">
    <button @click="showA = !showA">切换{{ showA }}</button>
    <component :is="showA ? componentA : componentB" />
  </div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import componentA from "@/components/componentA.vue";
import componentB from "@/components/componentB.vue";
const showA = ref(true);
</script>

页面,使用KeepAlive:

html 复制代码
<template>
  <div class="page">
    <button @click="showA = !showA">切换{{ showA }}</button>
    <KeepAlive>
      <component :is="showA ? componentA : componentB" />
    </KeepAlive>
  </div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import componentA from "@/components/componentA.vue";
import componentB from "@/components/componentB.vue";
const showA = ref(true);
</script>

三、缓存组件的包含/排除

默认情况下,<KeepAlive></KeepAlive>能缓存包裹的所有组件,但我们可以通过 includeexclude prop 来定制该行为。这两个 prop 的值都可以是一个以英文逗号分隔的字符串、一个正则表达式,或是包含这两种类型的一个数组:

html 复制代码
<!-- 以英文逗号分隔的字符串 -->
<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>

四、最大缓存实例数

通过max的值来限制缓存的实例数,如果缓存的实例数量即将超过指定的那个最大数量,则最久没有被访问的缓存实例将被销毁,以便为新的实例腾出空间。

html 复制代码
<KeepAlive :max="10">
  <component :is="activeComponent" />
</KeepAlive>

五、缓存实例的生命周期

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

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

html 复制代码
<script setup>
import { onActivated, onDeactivated } from 'vue'

onActivated(() => {
  // 调用时机为首次挂载
  // 以及每次从缓存中被重新插入时
})

onDeactivated(() => {
  // 在从 DOM 上移除、进入缓存
  // 以及组件卸载时调用
})
</script>

六、参考文档

Vue.js - 渐进式 JavaScript 框架 | Vue.js

相关推荐
jingling5553 分钟前
面试版-前端开发核心知识
开发语言·前端·javascript·vue.js·面试·前端框架
拾光拾趣录8 分钟前
CSS 深入解析:提升网页样式技巧与常见问题解决方案
前端·css
莫空00009 分钟前
深入理解JavaScript属性描述符:从数据属性到存取器属性
前端·面试
guojl10 分钟前
深度剖析Kafka读写机制
前端
FogLetter11 分钟前
图片懒加载:让网页飞起来的魔法技巧 ✨
前端·javascript·css
Mxuan11 分钟前
vscode webview 插件开发(精装篇)
前端
Mxuan12 分钟前
vscode webview 插件开发(交付篇)
前端
Mxuan14 分钟前
vscode 插件与 electron 应用跳转网页进行登录的实践
前端
拾光拾趣录14 分钟前
JavaScript 加载对浏览器渲染的影响
前端·javascript·浏览器
Codebee14 分钟前
OneCode图表配置速查手册
大数据·前端·数据可视化