在 Vue 3 中,如何缓存和复用动态组件

news2025/2/28 6:15:18

在 Vue 3 中,如何缓存和复用动态组件,这有助于提高应用的性能,避免组件重复创建和销毁带来的开销。下面详细介绍其使用方法和相关配置。

1. 使用 <KeepAlive> 组件缓存动态组件

基本使用

<KeepAlive> 是 Vue 3 内置的一个组件,它可以将包裹在其中的动态组件进行缓存,当组件被切换隐藏时,其状态会被保留,再次显示时无需重新创建。

<template>
  <div>
    <button @click="currentComponent = 'ComponentA'">显示组件 A</button>
    <button @click="currentComponent = 'ComponentB'">显示组件 B</button>
    <!-- 使用 KeepAlive 包裹动态组件 -->
    <KeepAlive>
      <component :is="currentComponent" />
    </KeepAlive>
  </div>
</template>

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

const currentComponent = ref('ComponentA');

const components = {
  ComponentA,
  ComponentB
};
</script>
代码解释
  • 在模板中,使用 <KeepAlive> 组件包裹 <component :is="currentComponent" />,这样 ComponentAComponentB 在切换时会被缓存。
  • currentComponent 是一个响应式变量,用于控制显示哪个组件。

包含和排除特定组件

你可以使用 includeexclude 属性来指定哪些组件需要被缓存或排除。这两个属性的值可以是组件名称的字符串、正则表达式或数组。

<template>
  <div>
    <button @click="currentComponent = 'ComponentA'">显示组件 A</button>
    <button @click="currentComponent = 'ComponentB'">显示组件 B</button>
    <!-- 只缓存 ComponentA -->
    <KeepAlive include="ComponentA">
      <component :is="currentComponent" />
    </KeepAlive>
  </div>
</template>

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

const currentComponent = ref('ComponentA');

const components = {
  ComponentA,
  ComponentB
};
</script>
代码解释
  • include="ComponentA" 表示只有 ComponentA 会被缓存,ComponentB 不会被缓存,每次切换到 ComponentB 时都会重新创建。
  • 若使用 exclude 属性,则与之相反,被排除的组件不会被缓存。例如 <KeepAlive exclude="ComponentB"> 会缓存除 ComponentB 之外的组件。

最大缓存实例数

你可以使用 max 属性来限制 <KeepAlive> 缓存的最大实例数量。当缓存的实例数量超过 max 值时,最早缓存的实例会被销毁。

<template>
  <div>
    <button @click="currentComponent = 'ComponentA'">显示组件 A</button>
    <button @click="currentComponent = 'ComponentB'">显示组件 B</button>
    <button @click="currentComponent = 'ComponentC'">显示组件 C</button>
    <!-- 最多缓存 2 个组件实例 -->
    <KeepAlive max="2">
      <component :is="currentComponent" />
    </KeepAlive>
  </div>
</template>

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

const currentComponent = ref('ComponentA');

const components = {
  ComponentA,
  ComponentB,
  ComponentC
};
</script>
代码解释
  • max="2" 表示 <KeepAlive> 最多缓存 2 个组件实例。当切换到第三个组件时,最早缓存的组件实例会被销毁。

组件缓存状态的生命周期钩子

当组件被 <KeepAlive> 缓存时,会有两个特殊的生命周期钩子 onActivatedonDeactivated,可以在这两个钩子中执行相应的逻辑。

<template>
  <div>
    This is Component A.
  </div>
</template>

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

onActivated(() => {
  console.log('Component A is activated.');
});

onDeactivated(() => {
  console.log('Component A is deactivated.');
});
</script>
代码解释
  • onActivated:当组件被激活(从缓存中显示出来)时触发。
  • onDeactivated:当组件被停用(被隐藏并放入缓存)时触发。

通过上述方法,你可以在 Vue 3 中灵活地缓存和复用动态组件,提高应用的性能和用户体验。

2. 组件实例缓存(手动管理)

除了使用 <KeepAlive>,你还可以手动管理组件实例的缓存。通过一个对象来存储组件实例,在需要使用时从对象中获取。

<template>
  <div>
    <button @click="showComponent('ComponentA')">显示组件 A</button>
    <button @click="showComponent('ComponentB')">显示组件 B</button>
    <component :is="currentComponent" v-if="currentComponent" />
  </div>
</template>

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

// 存储组件实例的缓存对象
const componentCache = {};
const currentComponent = ref(null);

const showComponent = (name) => {
  if (!componentCache[name]) {
    const component = name === 'ComponentA' ? ComponentA : ComponentB;
    // 创建组件实例并存储到缓存中
    componentCache[name] = markRaw(shallowRef(component));
  }
  currentComponent.value = componentCache[name].value;
};
</script>
代码解释
  • componentCache 是一个对象,用于存储组件实例。
  • showComponent 方法根据传入的组件名称,检查缓存中是否存在该组件实例。如果不存在,则创建实例并存储到缓存中;如果存在,则直接从缓存中获取。

3. 组合式函数封装

可以将动态组件的逻辑封装到组合式函数中,提高代码的复用性。

// useDynamicComponent.js
import { ref, shallowRef, markRaw } from 'vue';

export function useDynamicComponent() {
  const componentCache = {};
  const currentComponent = ref(null);

  const showComponent = (name, component) => {
    if (!componentCache[name]) {
      componentCache[name] = markRaw(shallowRef(component));
    }
    currentComponent.value = componentCache[name].value;
  };

  return {
    currentComponent,
    showComponent
  };
}
<template>
  <div>
    <button @click="showComponent('ComponentA', ComponentA)">显示组件 A</button>
    <button @click="showComponent('ComponentB', ComponentB)">显示组件 B</button>
    <component :is="currentComponent" v-if="currentComponent" />
  </div>
</template>

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

const { currentComponent, showComponent } = useDynamicComponent();
</script>
代码解释
  • useDynamicComponent 组合式函数封装了动态组件的缓存和显示逻辑。
  • 在组件中使用该组合式函数,通过调用 showComponent 方法来显示不同的组件。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2307241.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【PromptCoder】使用 package.json 生成 cursorrules

【PromptCoder】使用 package.json 生成 cursorrules 在当今快节奏的开发世界中&#xff0c;效率和准确性至关重要。开发者们不断寻找能够优化工作流程、帮助他们更快编写高质量代码的工具。Cursor 作为一款 AI 驱动的代码编辑器&#xff0c;正在彻底改变我们的编程方式。但如…

给博客添加基于百度地图的足迹页面

使用百度地图 api 做的足迹页面一段时间了&#xff0c;经过一番改造&#xff0c;目前已基本能够满足自己需求。 一、添加百度地图 添加百度地图基本思路就是6点&#xff1a; 申请百度AK适当位置添加百度地图容器引入百度地图 api创建地图实例设置地图中心点初始化地图 这里…

【构建工具】Gradle Kotlin DSL中的大小写陷阱:BuildConfigField

在Android开发当中&#xff0c;BuildConfig是一个非常有用的功能&#xff0c;它允许我们在构建过程中定义常量&#xff0c;并在运行时使用它们。But&#xff01;&#xff01;当我们从传统的Groovy DSL迁移到Kotlin DSL时或者被Android Studio坑的时候&#xff0c;有一些细微的差…

4个小时开发DeepSeek+baiduNaotu一键生成思维导图

一、引言 最近发现AI生成思维导图的解决方案普遍存在两个断层&#xff1a;用户需手动复制模型输出的JSON数据到脑图软件&#xff0c;且缺乏实时可视化反馈。基于日常使用的BaiduNaotu框架&#xff08;其轻量级架构与简洁的UI设计已满足基础需求&#xff09;&#xff0c;我决定…

(21)从strerror到strtok:解码C语言字符函数的“生存指南2”

❤个人主页&#xff1a;折枝寄北的博客 ❤专栏位置&#xff1a;简单入手C语言专栏 目录 前言1. 错误信息报告1.1 strerror 2. 字符操作2.1 字符分类函数2.2 字符转换函数 3. 内存操作函数3.1 memcpy3.2 memmove3.2memset3.3 memcmp 感谢您的阅读 前言 当你写下strcpy(dest, s…

SpringBoot集成easy-captcha图片验证码框架

SpringBoot集成easy-captcha图片验证码框架 此项目已经很久未维护&#xff0c;如有更好的选择&#xff0c;建议使用更好的选择!!! 一、引言 验证码&#xff08;CAPTCHA&#xff09;是现代应用中防止机器人攻击、保护接口安全的核心手段之一。然而&#xff0c;从零开发验证码…

货车一键启动无钥匙进入手机远程启动的正确使用方法

一、移动管家货车无钥匙进入系统的使用方法 基本原理&#xff1a;无钥匙进入系统通常采用RFID无线射频技术和车辆身份识别码识别系统。车钥匙需要随身携带&#xff0c;当车钥匙靠近货车时&#xff0c;它会自动与货车的解码器匹配。开门操作&#xff1a;当靠近货车后&#xff0…

【实战 ES】实战 Elasticsearch:快速上手与深度实践-1.2.2倒排索引原理与分词器(Analyzer)

&#x1f449; 点击关注不迷路 &#x1f449; 点击关注不迷路 &#x1f449; 点击关注不迷路 文章大纲 1.2.2倒排索引原理与分词器&#xff08;Analyzer&#xff09;1. 倒排索引&#xff1a;搜索引擎的基石1.1 正排索引 vs 倒排索引示例数据对比&#xff1a; 1.2 倒排索引核心结…

和鲸科技携手四川气象,以 AI 的力量赋能四川气象一体化平台建设

气象领域与农业、能源、交通、环境科学等国计民生关键领域紧密相连&#xff0c;发挥着不可替代的重要作用。人工智能技术的迅猛发展&#xff0c;为气象领域突破困境带来了新的契机。AI 技术能够深度挖掘气象大数据中蕴含的复杂信息&#xff0c;助力人类更精准地把握自然规律&am…

linux下java Files.copy 提示文件名过长

linux下java Files.copy 提示文件名过长问题排查 系统运行时执行文件拷贝的功能的时候出现了 文件名称过长的报错提示 查询过资料后整理出了每个操作系统支持最大的文件名称长度 每个操作系统现在的文件长度不一样 Linux的 /usr/include/linux/limits.h 中做出了说明 这些限制…

Metal学习笔记八:纹理

到目前为止&#xff0c;您已经学习了如何使用片段函数和着色器为模型添加颜色和细节。另一种选择是使用图像纹理&#xff0c;您将在本章中学习如何作。更具体地说&#xff0c;您将了解&#xff1a; • UV 坐标&#xff1a;如何展开网格&#xff0c;以便可以对其应用纹理。 • 纹…

Idea 和 Pycharm 快捷键

一、快捷键 二、Pycharm 中怎么切换分支 参考如下 如果在界面右下角 没有看到当前所在的分支&#xff0c;如 “Git:master” 3. 有了 4.

fody引用c++的dll合并后提示找不到

fody引用c的dll合并后提示找不到 解决方案&#xff1a; 在 FodyWeavers.xml 文件中添加配置 CreateTemporaryAssemblies‘true’ 官方文档&#xff1a;https://github.com/Fody/Costura <Weavers xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance" xsi:noN…

初识flutter1

为什么使用flutter, 说直白一点,就是移动UI框架, 个人认为优势是: 1.一套代码adnroid 和ios 可以使用, 代码好维护 2.原生用户界面 3.开源、免费的 开发工具&#xff1a; 1.下载 java 包, 根据自己的电脑配置选择 官网下载: https://www.oracle.com/java/technologies/download…

12字符函数

一、函数strchr与strrchr 注意&#xff1a; 这两个函数的功能&#xff0c;都是在指定的字符串 s 中&#xff0c;试图找到字符 c。strchr() 从左往右找&#xff0c;strrchr() 从右往左找。字符串结束标记 ‘\0’ 被认为是字符串的一部分。 图解&#xff1a; 示例代码&#xff…

QT6开发高性能企业视频会议-8 使用VSCode+Copilot AI开发

Github Copilot是Github和OpenAI推出的AI编程辅助工具&#xff0c;之前版本的Github Copilot只有简单的代码自动补全&#xff0c;根据注释生成一些代码等辅助功能。 近期Copilot有了一次大的升级&#xff0c;加入了Agent模式&#xff0c;可以实现自然语言对话讨论和最重要的&a…

矩阵的奇异值(SVD)分解和线性变换

矩阵的奇异值&#xff08;SVD&#xff09;分解和线性变换 SVD定义 奇异值分解&#xff08;Singular Value Decomposition&#xff0c;简称 SVD&#xff09;是一种重要的线性代数工具&#xff0c;能够将任意矩阵 ( A ∈ R m n \mathbf{A} \in \mathbb{R}^{m \times n} A∈Rmn…

数据库的sql语句

本篇文章主要用来收集项目开发中&#xff0c;遇到的各种sql语句的编写。 1、根据user表的role_id字段&#xff0c;查询role表。 sql语句&#xff1a;使用JOIN连接两个表 SELECT u.*,r.rolename FROM user u JOIN role r ON u.role_id r.id WHERE u.id 1; 查询结果&#xff1a…

Ubuntu2204下使用NVIDIA GeForce RTX 4090进行DeepSeek-R1-Distill-Llama-8B模型微调

Ubuntu2204下使用NVIDIA GeForce RTX 4090进行DeepSeek-R1-Distill-Llama-8B模型微调 环境准备创建Python微调环境准备数据集准备模型文件 模型微调模型预测原始模型预测微调模型预测 使用unsloth&#xff0c;可以方便地对大模型进行微调。以微调DeepSeek-R1-Distill-Llama-8B为…

Bugku CTF Crypto(二)

目录 这不是md5 贝斯家族 把猪困在猪圈里 黄道十二官&#xff08;宫&#xff09; 抄错的字符 这不是md5 描 述: 666c61677b616537333538376261353662616566357d 分 析&#xff1a;题目提示这不是md5&#xff0c;字符中出现了d&#xff0c;猜测16进制 使用…