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

相关推荐
前端小白佬10 分钟前
【JS】防抖(debounce)和节流(throttle)
前端·面试
GIS之路12 分钟前
OpenLayers 从后端服务加载 GeoJSON 数据
前端
开始编程吧19 分钟前
【HarmonyOS5】仓颉编程:当多范式统一成为智能时代的「通用语言」
前端
PasserbyX29 分钟前
ES6 WeakMap 生效的证明: FinalizationRegistry
前端·javascript
努力学习的小刘32 分钟前
如何使用react-router实现动态路由
前端·javascript
PasserbyX32 分钟前
JS原型链
前端·javascript
curdcv_po32 分钟前
你知道Cookie的弊端吗?
前端
curdcv_po34 分钟前
前端CSS高频面试题详解
前端
Danta38 分钟前
从0开始学习three.js(1)😁
前端·javascript·three.js
我的心巴38 分钟前
vue-print-nb 打印相关问题
前端·vue.js·elementui