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

相关推荐
前端涂涂几秒前
UniApp 实现兼容 H5 和小程序的拖拽排序组件
前端
养军博客1 分钟前
封装uniapp request promise化
前端·javascript·uni-app
lovemiss2 分钟前
web性能优化(一)字体包优化
前端
不辉放弃12 分钟前
第三章:SQL 高级功能与性能优化
服务器·前端·sql·mysql
石小石Orz23 分钟前
牛逼!只需一行代码,任意网页秒变可编辑!
前端
玖玖passion24 分钟前
深入浅出WebSocket:实时通信的新时代
前端
程序猿chen1 小时前
Vue.js组件化开发实战:从工程化到安全纵深设计
前端·vue.js·安全
BillKu1 小时前
vue3中watch的使用示例
前端·javascript·vue.js
金色的暴发户1 小时前
苦尽甘来终有时,一路向阳待花开
前端·javascript·面试
摆烂工程师2 小时前
Grok3 API 已经全网上线了!并且 Grok3 API 可以免费使用
前端·后端·程序员