vue3中keep-alive

293 阅读2分钟

vue3中keep-alive

在 Vue 3 中,<keep-alive> 是一个内置组件,用于缓存动态组件的状态,避免组件在切换时被销毁和重新创建。通过 keep-alive,可以提升应用的性能,特别是在需要频繁切换组件的场景中。

以下是 keep-alive 的详细解析和使用方法。

  1. keep-alive 的作用

keep-alive 的主要功能是缓存组件的状态,包括:

  • 组件实例:避免组件被销毁和重新创建。

  • 组件状态:保留组件的内部状态(如数据、DOM 状态等)。

  • 生命周期钩子:触发 activateddeactivated 钩子,而不是 mountedunmounted

  1. 基本用法

将需要缓存的组件包裹在 <keep-alive> 标签中。

缓存动态组件

<template>
  <div>
    <button @click="currentComponent = 'ComponentA'">Show Component A</button>
    <button @click="currentComponent = 'ComponentB'">Show Component B</button>

    <keep-alive>
      <component :is="currentComponent" />
    </keep-alive>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';

const currentComponent = ref('ComponentA');
</script>

在上面的例子中,ComponentAComponentB 在切换时不会被销毁,而是被缓存。

  1. includeexclude

keep-alive 支持通过 includeexclude 属性指定需要缓存或排除的组件。

(1) include

只缓存指定的组件。

缓存指定组件

<keep-alive include="ComponentA,ComponentB">
  <component :is="currentComponent" />
</keep-alive>

(2) exclude

排除指定的组件。

排除指定组件

<keep-alive exclude="ComponentC">
  <component :is="currentComponent" />
</keep-alive>
  1. max 属性

keep-alive 支持通过 max 属性限制缓存的组件实例数量。当缓存的实例数量超过 max 时,最早被缓存的实例会被销毁。

限制缓存数量

<keep-alive :max="2">
  <component :is="currentComponent" />
</keep-alive>
  1. 生命周期钩子

keep-alive 缓存的组件会触发以下生命周期钩子:

  • activated:组件被激活时触发(从缓存中恢复)。

  • deactivated:组件被停用时触发(进入缓存)。

使用生命周期钩子

export default {
  activated() {
    console.log('Component activated');
  },
  deactivated() {
    console.log('Component deactivated');
  },
};
  1. 结合路由使用

keep-alive 常用于缓存路由组件,提升页面切换的性能。

缓存路由组件

<template>
  <router-view v-slot="{ Component }">
    <keep-alive>
      <component :is="Component" />
    </keep-alive>
  </router-view>
</template>
  1. 注意事项

内存占用keep-alive 会缓存组件实例,可能导致内存占用增加,需合理使用。

动态组件keep-alive 只能缓存动态组件(通过 is 属性绑定的组件)。

状态丢失:如果组件被销毁(如超出 max 限制),状态会丢失。

  1. 总结

keep-alive 是 Vue 3 中用于缓存组件状态的重要工具,适用于需要频繁切换组件的场景。通过 includeexcludemax 属性,可以灵活控制缓存行为。结合路由使用,可以显著提升页面切换的性能和用户体验。

更多vue相关插件及后台管理模板可访问vue admin reference,代码详情请访问github