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

相关推荐
余生H9 分钟前
前端的全栈混合之路Meteor篇:关于前后端分离及与各框架的对比
前端·javascript·node.js·全栈
花花鱼10 分钟前
@antv/x6 导出图片下载,或者导出图片为base64由后端去处理。
vue.js
程序员-珍12 分钟前
使用openapi生成前端请求文件报错 ‘Token “Integer“ does not exist.‘
java·前端·spring boot·后端·restful·个人开发
axihaihai16 分钟前
网站开发的发展(后端路由/前后端分离/前端路由)
前端
流烟默28 分钟前
Vue中watch监听属性的一些应用总结
前端·javascript·vue.js·watch
2401_8572979139 分钟前
招联金融2025校招内推
java·前端·算法·金融·求职招聘
茶卡盐佑星_1 小时前
meta标签作用/SEO优化
前端·javascript·html
Ink1 小时前
从底层看 path.resolve 实现
前端·node.js
金灰1 小时前
HTML5--裸体回顾
java·开发语言·前端·javascript·html·html5
茶卡盐佑星_1 小时前
说说你对es6中promise的理解?
前端·ecmascript·es6