vue之KeepAlive 组件缓存

简单使用

<!-- 非活跃的组件将会被缓存! -->
<KeepAlive>
  <component :is="activeComponent" />
</KeepAlive>

讲解

默认会缓存内部的所有组件实例,但我们可以通过 include 和 exclude 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 选项。
这个name对应的就是vue文件里面js声明的组件的name名。vue3 setup 会自动生成name即vue文件的名字。

激活,再次返回时怎么触发,执行新的操作

// vue3
<script setup>
import { onActivated, onDeactivated } from 'vue'

onActivated(() => {
  console.log('进入该组件时执行')
  // 调用时机为首次挂载
  // 以及每次从缓存中被重新插入时
})

onDeactivated(() => {
  console.log('离开该组件时执行')
  // 在从 DOM 上移除、进入缓存
  // 以及组件卸载时调用
})
</script>
// 再次返回组件时可以通过以上生命周期来获取感知从而执行新的操作

配合RouterView 使用

<router-view v-slot="{ Component }">
      <keep-alive>
        <component :is="Component" />
      </keep-alive>
    </router-view>

官网原文 https://cn.vuejs.org/guide/built-ins/keep-alive.html

posted @ 2023-01-10 19:28  LC蜗牛  阅读(329)  评论(0编辑  收藏  举报