动态组件与异步组件

动态组件与异步组件

动态组件解决"当前应该显示哪个组件",异步组件解决"这个组件的代码何时加载"。一个关注运行时的组件切换,一个关注代码的按需加载,二者可以组合,但不能混为一谈。

上一篇《插槽Slot详解》通过内容分发让组件结构更加灵活。本文继续讨论组件组合:如何在多个面板之间切换、如何保留切换前的状态,以及如何只在需要时下载组件代码。

写作约定 :示例以 Vue 3 <script setup> 和 Vite 为主。defineAsyncComponent、<KeepAlive> 的 include、exclude、max 均使用 Vue 3 API;defineOptions 需要 Vue 3.3+。文中"减少首屏代码"指把组件拆入独立 chunk,是否真正改善性能仍需结合实际构建与网络情况验证。


一、动态组件与异步组件分别解决什么问题

先看两个常见需求:

  • 用户点击"个人资料""账号设置""操作日志"页签时,内容区域需要显示不同组件;
  • 操作日志很少被打开,不希望它的代码和依赖进入首屏资源。

第一个需求使用动态组件:

vue 复制代码
<component :is="currentComponent" />

第二个需求使用异步组件:

js 复制代码
const LogPanel = defineAsyncComponent(() => import('./LogPanel.vue'))

它们可以组合使用:运行时决定显示哪个组件,而候选组件在第一次需要时才加载。

能力 动态组件 异步组件
主要目标 运行时切换组件 按需加载组件定义
常见 API <component :is> defineAsyncComponent
是否必然拆分构建产物 否 动态 import() 通常会产生独立 chunk
是否保留组件状态 默认不保留,可配合 KeepAlive 与加载方式无直接关系
是否自动处理加载失败 不涉及 可配置加载与错误状态

理解这个区别后,后面的 API 就不会混在一起。


二、动态组件的基本用法

假设有三个已经同步注册的组件:

vue 复制代码
<!-- App.vue -->
<script setup>
import { shallowRef } from 'vue'
import ProfilePanel from './components/ProfilePanel.vue'
import SecurityPanel from './components/SecurityPanel.vue'
import LogPanel from './components/LogPanel.vue'

const tabs = [
  { key: 'profile', label: '个人资料', component: ProfilePanel },
  { key: 'security', label: '账号安全', component: SecurityPanel },
  { key: 'log', label: '操作日志', component: LogPanel }
]

const activeKey = shallowRef('profile')
const activeComponent = shallowRef(ProfilePanel)

function selectTab(tab) {
  activeKey.value = tab.key
  activeComponent.value = tab.component
}
</script>

<template>
  <nav aria-label="账号设置">
    <button
      v-for="tab in tabs"
      :key="tab.key"
      type="button"
      :aria-pressed="activeKey === tab.key"
      @click="selectTab(tab)"
    >
      {{ tab.label }}
    </button>
  </nav>

  <component :is="activeComponent" />
</template>

<component> 是内置元素,:is 决定实际渲染的组件。这里传入的是组件定义,而不是组件名称字符串。

为什么使用 shallowRef

组件定义不需要被 Vue 深度转换为响应式对象。保存组件定义时使用 shallowRef 或 markRaw,可以避免不必要的深度响应式处理以及相关警告。

js 复制代码
import { markRaw, ref } from 'vue'

const tabs = ref([
  { key: 'profile', component: markRaw(ProfilePanel) }
])

如果组件列表从模块加载后就不再变化,也可以不使用响应式包装:

js 复制代码
const tabMap = {
  profile: ProfilePanel,
  security: SecurityPanel,
  log: LogPanel
}
const activeKey = shallowRef('profile')
const activeComponent = computed(() => tabMap[activeKey.value])

此时需要额外导入 computed。


三、根据页面数据选择组件

实际项目中,页签通常由配置生成。推荐保存稳定的 key,再通过映射取得组件,而不是把组件定义直接塞进接口响应或本地存储。

vue 复制代码
<script setup>
import { computed, shallowRef } from 'vue'
import TextQuestion from './questions/TextQuestion.vue'
import SingleChoiceQuestion from './questions/SingleChoiceQuestion.vue'
import MultipleChoiceQuestion from './questions/MultipleChoiceQuestion.vue'

const questionComponents = {
  text: TextQuestion,
  single: SingleChoiceQuestion,
  multiple: MultipleChoiceQuestion
}

const currentQuestion = shallowRef({
  id: 1,
  type: 'single',
  title: '你常用的 Vue 版本是?'
})

const currentComponent = computed(() => {
  return questionComponents[currentQuestion.value.type] ?? TextQuestion
})
</script>

<template>
  <component
    :is="currentComponent"
    :question="currentQuestion"
  />
</template>

这里的兜底组件可以避免未知类型导致内容区域完全空白。生产环境还应记录未知类型,并尽量在接口边界完成数据校验。

如果确需使用全局注册的组件名,也可以传字符串:

vue 复制代码
<component :is="'ProfilePanel'" />

但字符串依赖全局注册名称,重构和类型检查不如直接引用组件定义直观。局部组件优先使用组件对象映射。


四、传递 Props、事件与插槽

动态组件仍然是一个普通组件,Props 和事件照常传递:

vue 复制代码
<component
  :is="activeComponent"
  :user-id="userId"
  :editable="true"
  @saved="handleSaved"
/>

候选组件最好具有一致的基础契约。例如三个设置面板都接收 userId,并发出 saved 事件。如果某个面板需要额外参数,可以使用计算属性按类型组织:

vue 复制代码
<component
  :is="activeComponent"
  v-bind="activeProps"
  @saved="handleSaved"
/>

不要把所有可能参数无条件塞给每个组件。无关属性可能透传到根元素,也会让组件边界难以维护。

插槽同样可以使用:

vue 复制代码
<component :is="activeComponent">
  <template #footer>
    <button type="button" @click="save">保存</button>
  </template>
</component>

前提是候选组件确实声明了对应插槽。动态切换并没有改变 Props、事件和插槽的基本规则。


五、为什么切换后表单状态会丢失

不使用缓存时,旧组件会被卸载,新组件会被挂载:

vue 复制代码
<component :is="activeComponent" />

从"个人资料"切到"账号安全"后,个人资料组件已经销毁。再切回来时会创建新实例,因此未保存的输入、滚动位置和内部请求状态通常会重置。

这是正常的生命周期行为,不是动态组件故障。如果产品要求保留页签状态,可以使用内置组件 <KeepAlive>:

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

此时被切走的组件实例会被缓存,而不是立即卸载;切回时复用原实例。

是否使用缓存应该由交互需求决定:

  • 页签包含未提交表单,通常需要保留;
  • 每次进入都必须展示最新数据,可以在激活时刷新;
  • 页面包含大量重型面板,应限制缓存数量或主动清理;
  • 涉及敏感信息时,还要考虑退出登录、切换账号后的缓存清理。

六、KeepAlive 的筛选与缓存上限

6.1 include 与 exclude

include 只缓存匹配的组件,exclude 排除匹配的组件:

vue 复制代码
<KeepAlive include="ProfilePanel,SecurityPanel">
  <component :is="activeComponent" />
</KeepAlive>

也可以传数组或正则表达式:

vue 复制代码
<KeepAlive :include="['ProfilePanel', 'SecurityPanel']">
  <component :is="activeComponent" />
</KeepAlive>

名称匹配的是组件的 name。在 <script setup> 中可以通过 defineOptions 明确声明:

vue 复制代码
<script setup>
defineOptions({ name: 'ProfilePanel' })
</script>

不要只依据文件名猜测运行时名称,尤其是经过异步包装、高阶组件或自动导入插件处理后,应结合 Devtools 验证。

6.2 max 限制缓存数量

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

当缓存实例数量超过上限时,最久未被访问的实例会被移除。max 能限制无限增长,但不等于完整的内存管理方案;大型列表、定时器和外部订阅仍需在组件中正确清理。


七、缓存组件的激活与停用

被缓存的组件不能只依赖 onMounted 和 onUnmounted。还应使用 onActivated 与 onDeactivated:

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

onMounted(() => {
  console.log('实例首次挂载')
})

onActivated(() => {
  console.log('进入或重新进入面板')
})

onDeactivated(() => {
  console.log('面板被切走')
})
</script>

一个常见策略是首次挂载加载数据,重新激活时按业务需要刷新:

vue 复制代码
<script setup>
import { onActivated, ref } from 'vue'
import { fetchOperationLogs } from '../api/logs'

const logs = ref([])
const loading = ref(false)

async function loadLogs() {
  loading.value = true
  try {
    logs.value = await fetchOperationLogs()
  } finally {
    loading.value = false
  }
}

onActivated(loadLogs)
</script>

如果每次激活都会请求,还应处理快速切换造成的响应乱序,并避免重复并发请求。缓存保留了旧状态,但不保证旧数据仍然新鲜。


八、异步组件:第一次需要时再加载

同步导入会让组件进入当前模块的依赖图:

js 复制代码
import LogPanel from './components/LogPanel.vue'

使用 defineAsyncComponent 和动态 import():

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

const LogPanel = defineAsyncComponent(() => import('./components/LogPanel.vue'))
</script>

<template>
  <LogPanel />
</template>

LogPanel 仍然可以像普通组件一样使用。只有渲染到它时,加载函数才会执行,浏览器随后请求对应模块。

动态导入还允许构建工具拆分代码,但它不会自动带来以下保证:

  • 首屏一定更快;
  • 总体积一定更小;
  • 请求数量一定更少;
  • 用户切换时一定没有等待。

如果组件很小、几乎必然立即显示,拆分反而可能增加请求与等待。异步组件更适合大型图表编辑器、复杂弹窗、低频页签和路由页面等场景。


九、加载中与加载失败

网络请求可能慢,也可能失败。defineAsyncComponent 提供加载和错误组件配置:

vue 复制代码
<script setup>
import { defineAsyncComponent } from 'vue'
import PanelLoading from './components/PanelLoading.vue'
import PanelLoadError from './components/PanelLoadError.vue'

const ReportPanel = defineAsyncComponent({
  loader: () => import('./components/ReportPanel.vue'),
  loadingComponent: PanelLoading,
  errorComponent: PanelLoadError,
  delay: 200,
  timeout: 10000
})
</script>

<template>
  <ReportPanel />
</template>

主要选项含义如下:

选项 作用
loader 返回组件定义或 Promise 的加载函数
loadingComponent 加载期间显示的组件
errorComponent 加载失败或超时时显示的组件
delay 延迟显示加载组件,避免短暂闪烁
timeout 等待上限,超时后展示错误组件

delay: 200 不是延迟开始下载,而是延迟显示加载状态。timeout 也不会替业务请求设置超时,它只作用于组件加载。

错误组件应提供可操作的反馈。仅显示"加载失败"会让用户无路可走,实际项目中通常还需要重试入口和错误日志。


十、为异步组件增加重试

加载失败后,可以重新创建异步组件定义,并通过 key 触发替换:

vue 复制代码
<script setup>
import { defineAsyncComponent, shallowRef } from 'vue'
import PanelLoading from './components/PanelLoading.vue'
import PanelLoadError from './components/PanelLoadError.vue'

const reportKey = shallowRef(0)
const reportComponent = shallowRef(createReportComponent())

function createReportComponent() {
  return defineAsyncComponent({
    loader: () => import('./components/ReportPanel.vue'),
    loadingComponent: PanelLoading,
    errorComponent: PanelLoadError,
    timeout: 10000
  })
}

function retryReport() {
  reportComponent.value = createReportComponent()
  reportKey.value += 1
}
</script>

<template>
  <component :is="reportComponent" :key="reportKey" />
  <button type="button" @click="retryReport">重新加载报表组件</button>
</template>

这里的重试按钮应放在父组件中,确保错误组件显示时入口仍然存在。

需要区分两类失败:

  • 模块网络请求失败:重试动态导入;
  • 组件内部接口失败:由组件的数据请求逻辑重试。

给所有动态导入盲目增加多次重试可能放大网络问题,应结合错误监控与用户操作设计。


十一、动态组件与异步组件组合实战

下面把两部分组合成账号中心。三个面板都按需加载,前两个保留状态,日志面板每次激活获取新数据。

vue 复制代码
<!-- AccountCenter.vue -->
<script setup>
import { computed, defineAsyncComponent, shallowRef } from 'vue'
import PanelLoading from './components/PanelLoading.vue'
import PanelLoadError from './components/PanelLoadError.vue'

const asyncOptions = {
  loadingComponent: PanelLoading,
  errorComponent: PanelLoadError,
  delay: 200,
  timeout: 10000
}

const panels = {
  profile: defineAsyncComponent({
    ...asyncOptions,
    loader: () => import('./panels/ProfilePanel.vue')
  }),
  security: defineAsyncComponent({
    ...asyncOptions,
    loader: () => import('./panels/SecurityPanel.vue')
  }),
  log: defineAsyncComponent({
    ...asyncOptions,
    loader: () => import('./panels/LogPanel.vue')
  })
}

const activeKey = shallowRef('profile')
const activeComponent = computed(() => panels[activeKey.value])
</script>

<template>
  <button type="button" @click="activeKey = 'profile'">个人资料</button>
  <button type="button" @click="activeKey = 'security'">账号安全</button>
  <button type="button" @click="activeKey = 'log'">操作日志</button>

  <KeepAlive include="ProfilePanel,SecurityPanel">
    <component
      :is="activeComponent"
      :key="activeKey"
      user-id="1001"
    />
  </KeepAlive>
</template>

各面板明确声明名称:

vue 复制代码
<!-- ProfilePanel.vue -->
<script setup>
defineOptions({ name: 'ProfilePanel' })
defineProps({ userId: { type: String, required: true } })
</script>

<template>
  <section>个人资料</section>
</template>

这里 :key="activeKey" 用于区分不同面板实例。KeepAlive 的筛选依据仍是组件名称,不是这个 key。

如果异步组件的缓存筛选没有按预期工作,应检查实际组件名称和 Vue 版本,不要盲目给所有面板都加缓存。


十二、预加载:在需要之前悄悄准备

按需加载减少了立即执行的代码,却可能把等待推迟到点击之后。可以在用户表现出意图时预加载,例如鼠标悬停或键盘聚焦页签:

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

const loadReportPanel = () => import('./components/ReportPanel.vue')
const ReportPanel = defineAsyncComponent(loadReportPanel)
</script>

<template>
  <button
    type="button"
    @mouseenter="loadReportPanel"
    @focus="loadReportPanel"
  >
    查看报表
  </button>
  <ReportPanel />
</template>

模块加载会由浏览器和模块系统复用,不必为每次悬停手写一套缓存 Promise。不过,模板会在初次渲染时加载 ReportPanel,所以更合理的场景是把组件放在点击后才显示的区域:

vue 复制代码
<script setup>
import { defineAsyncComponent, shallowRef } from 'vue'

const loadReportPanel = () => import('./components/ReportPanel.vue')
const ReportPanel = defineAsyncComponent(loadReportPanel)
const showReport = shallowRef(false)
</script>

<template>
  <button
    type="button"
    @mouseenter="loadReportPanel"
    @focus="loadReportPanel"
    @click="showReport = true"
  >
    查看报表
  </button>
  <ReportPanel v-if="showReport" />
</template>

预加载也是一种资源竞争。弱网环境下不要一次预取所有低频页面,应优先保障当前可见内容。


十三、路由懒加载与局部异步组件

Vue Router 的路由懒加载本质上也是动态导入:

js 复制代码
const routes = [
  {
    path: '/reports',
    component: () => import('./views/ReportView.vue')
  }
]

它按页面拆分代码;defineAsyncComponent 更适合页面内部的局部组件。两者可以组合:

  • 路由级:进入报表页面时才加载页面模块;
  • 组件级:打开高级图表弹窗时才加载图表编辑器。

不要把每个按钮、标题和小卡片都异步化。拆分的粒度越大,加载边界越容易管理;拆分越碎,请求、加载状态和错误处理成本越高。


十四、TypeScript 中的组件映射

在 TypeScript 项目中,可以使用 Vue 的 Component 类型约束映射:

ts 复制代码
import type { Component } from 'vue'
import ProfilePanel from './panels/ProfilePanel.vue'
import SecurityPanel from './panels/SecurityPanel.vue'

const panels: Record<string, Component> = {
  profile: ProfilePanel,
  security: SecurityPanel
}

如果页签键只有固定几种,可以进一步使用联合类型:

ts 复制代码
type PanelKey = 'profile' | 'security'

const panels: Record<PanelKey, Component> = {
  profile: ProfilePanel,
  security: SecurityPanel
}

const activeKey = shallowRef<PanelKey>('profile')

类型只能约束组件映射和键值,不能自动证明所有组件都接受相同 Props。复杂面板可以提取共同的 Props 与事件契约,并通过类型检查或组件测试保证一致性。


十五、Vue 2 项目中的对应写法

Vue 2.3+ 支持异步组件工厂函数,配合动态导入可以写成:

js 复制代码
const ReportPanel = () => import('./ReportPanel.vue')

动态组件与缓存同样使用:

vue 复制代码
<keep-alive>
  <component :is="activeComponent" />
</keep-alive>

但 Vue 2 已停止维护,新旧版本在异步组件配置、组合式 API、构建工具和 TypeScript 支持方面存在差异。维护旧项目时应以实际 Vue 2 小版本和官方历史文档为准,不要直接照搬 Vue 3 的 defineAsyncComponent。


十六、常见误区与性能边界

16.1 把动态组件当成异步组件

vue 复制代码
<component :is="activeComponent" />

如果所有候选组件都通过静态 import 引入,它们仍会进入当前依赖图。动态切换不会自动拆分代码。

16.2 给每次渲染都创建新的异步定义

不要在渲染函数或计算属性中反复调用 defineAsyncComponent:

js 复制代码
// 不推荐:每次计算都会创建新的组件定义
const activeComponent = computed(() => {
  return defineAsyncComponent(() => import('./ReportPanel.vue'))
})

应在模块作用域或稳定的初始化阶段创建定义,避免重复加载状态和实例替换。

16.3 认为 KeepAlive 会缓存所有内部状态

KeepAlive 缓存组件实例,但不会替你管理所有外部状态。浏览器滚动容器、第三方编辑器、全局 Store 和手动创建的 DOM 对象需要分别验证。

16.4 忽略退出登录后的缓存

退出登录时,如果缓存仍保留上一个用户的组件实例,再次登录可能看到旧数据。应在账号切换时重置动态页签、清理相关状态,必要时通过外层 key 重建缓存区域:

vue 复制代码
<KeepAlive :key="currentUserId">
  <component :is="activeComponent" />
</KeepAlive>

是否使用这种方式要结合缓存结构设计,并验证不会残留其他用户数据。

16.5 拆分越多越专业

性能优化应基于构建产物和真实指标。可以使用构建分析工具观察 chunk,再在浏览器 Network 和 Performance 面板验证加载时机、资源大小及主线程开销。


十七、常见问题自查

问题 推荐处理
<component> 没有渲染内容 检查 :is 是否为有效组件定义或已注册名称
切换页签后表单被重置 确认是否需要 KeepAlive,并检查组件是否正确被缓存
include 不生效 核对组件 name、异步包装及 include 格式
每次激活都重复请求 区分首次加载与刷新策略,增加请求状态和取消机制
点击后才出现长时间空白 配置加载组件,必要时在意图阶段预加载
动态导入后仍没有独立 chunk 检查导入写法、构建配置和模块是否被其他同步入口引用
加载失败只有空白或报错 配置错误组件,提供父级重试入口并记录错误
异步组件 Props 丢失 检查加载结果是否为正确组件,以及 Props 是否正常声明
缓存导致旧用户数据出现 退出或切换账号时清理状态并重建相应缓存边界
组件很多时内存持续上涨 限制 max,减少缓存范围,清理定时器和外部订阅
组件看似没有异步加载 确认首次渲染位置,检查是否已被静态导入或提前预取
重试数据接口却重建组件 将模块加载失败与业务接口失败分开处理

十八、总结

动态组件和异步组件是两项可以协作的基础能力:

  1. <component :is> 根据运行时值选择要渲染的组件。
  2. 组件定义适合用 shallowRef、markRaw 或稳定映射管理,避免无意义的深度响应式转换。
  3. 动态组件仍遵循普通 Props、事件和插槽规则,候选组件应保持清晰契约。
  4. 普通切换会卸载旧实例,需要保留状态时可以使用 KeepAlive。
  5. include、exclude 和 max 控制缓存范围与数量,缓存组件还需考虑数据刷新和用户切换。
  6. defineAsyncComponent 配合动态 import() 按需加载组件,并通常形成独立构建 chunk。
  7. 加载组件、错误组件、延迟和超时让异步边界具备完整反馈。
  8. 模块加载失败与业务请求失败应分别处理,重试入口不能只存在于可能加载失败的子组件里。
  9. 路由懒加载与局部异步组件可以组合,但不应无差别拆分每个小组件。
  10. 最终是否优化了性能,应通过构建产物、网络请求和真实交互指标验证。

下一站预告

下一篇《组件生命周期详解》将系统梳理创建、挂载、更新、卸载以及缓存激活过程,进一步理解组件代码应该在什么时机执行。


作者:洋洋技术笔记

发布日期:2026-11-19

系列:Vue.js从入门到精通 - 第12篇


原文链接:洋洋的技术笔记

相关推荐
程序员大阳2 小时前
副队长Vue3教程(5)--事件绑定 v-on
前端·javascript·vue.js·vue3·事件绑定·v-on
OpenTiny社区4 小时前
我用Vue 100%复制DeepSeek开源的网页App,代码更少,功能还更多!
前端·vue.js·github
程序员大阳5 小时前
副队长Vue3教程(6)--script setup语法糖与ref基础响应式
vue.js·vue3·ref·script setup·基础响应式
1-1=05 小时前
Vue 条件渲染和列表渲染
前端·javascript·vue.js
徐小夕6 小时前
MedDoc AI:把临床书写、协作、质控、知识问答装进一个工作台
前端·vue.js·github
程序员大阳17 小时前
副队长Vue3教程(2)--Vite 搭建 Vue 项目,认识目录结构
前端·javascript·vue.js·vite·创建项目·目录结构·项目结构
北城笑笑19 小时前
Vue 110 ,若依SSE流式接口限次空500排查与解决
前端·javascript·vue.js·后端·vue
1-1=01 天前
Vue 中 Class 与 Style 绑定
前端·javascript·vue.js
闲来没事抠鼻屎1 天前
Web打印批量出单:vue-print-designer 千页实测
vue.js