探索 Vue3 (四) keep-alive缓存组件

keep-alive 的作用

官网介绍:KeepAlive | Vue.js

keep-alive为抽象组件,主要用于缓存内部组件数据状态。可以将组件缓存起来并在需要时重新使用,而不是每次重新创建。这可以提高应用的性能和用户体验,特别是在需要频繁切换组件时。

简单使用:

组件A

复制代码
<script setup>
import { ref } from 'vue'

const count = ref(0)
</script>

<template>
  <p>Current component: A</p>
  <span>count: {{ count }}</span>
  <button @click="count++">+</button>
</template>

组件B

复制代码
<script setup>
import { ref } from 'vue'
const msg = ref('')
</script>

<template>
  <p>Current component: B</p>
  <span>Message is: {{ msg }}</span>
  <input v-model="msg">
</template>

项目中使用:

复制代码
<script setup>
import { shallowRef } from 'vue'
import CompA from './CompA.vue'
import CompB from './CompB.vue'

const current = shallowRef(CompA)
</script>

<template>
  <div class="demo">
    <label><input type="radio" v-model="current" :value="CompA" /> A</label>
    <label><input type="radio" v-model="current" :value="CompB" /> B</label>
    <KeepAlive>
      <component :is="current"></component>
    </KeepAlive>
  </div>
</template>

运行之后可以看到切换组件对数据没有影响。

包含/排除

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

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

它会根据组件的 name 选项进行匹配,所以组件如果想要条件性地被 KeepAlive 缓存,就必须显式声明一个 name 选项。

这样子的话就只有CompA会生效,CompB没有include不会生效

最大缓存实例数

我们可以通过传入 max prop 来限制可被缓存的最大组件实例数。<KeepAlive> 的行为在指定了 max 后类似一个 LRU 缓存:如果缓存的实例数量即将超过指定的那个最大数量,则最久没有被访问的缓存实例将被销毁,以便为新的实例腾出空间。

template

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

缓存实例的生命周期

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

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

vue

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

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

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

请注意:

  • onActivated 在组件挂载时也会调用,并且 onDeactivated 在组件卸载时也会调用。

  • 这两个钩子不仅适用于 <KeepAlive> 缓存的根组件,也适用于缓存树中的后代组件。

相关推荐
玲小珑23 分钟前
Auto.js 入门指南(六)多线程与异步操作
android·前端
白瓷梅子汤25 分钟前
跟着官方示例学习 @tanStack-table --- Header Groups
前端·react.js
喝牛奶的小蜜蜂29 分钟前
个人小程序:不懂后台,如何做数据交互
前端·微信小程序·小程序·云开发
front_explorers34 分钟前
Umi项目必看,从Webpack到Rspack,KMI引领性能革命🚀
前端
旺仔牛仔QQ糖35 分钟前
都写那么多项目了, 傻傻分不清楚NODE_ENV 和 模式(Mode) 两者区别是什么
前端·面试
xcLeigh41 分钟前
HTML5实现简洁的体育赛事网站源码
前端·html
棉花糖超人44 分钟前
【从0-1的CSS】第1篇:CSS简介,选择器已经常用样式
前端·css
GISer_Jing1 小时前
XHR / Fetch / Axios 请求的取消请求与请求重试
前端·javascript·网络
天涯学馆1 小时前
微前端架构设计:从理论到实践的全面指南
前端·javascript·面试
Verin1 小时前
Next.js+Wagmi+rainbowkit构建以太坊合约交互模版
前端·web3·以太坊