Vue动态/异步组件
下面,我们来系统的梳理关于 Vue 动态组件 & 异步组件 的基本知识点:
一、动态组件核心概念
1.1 什么是动态组件?
动态组件是 Vue 中一种在运行时动态切换不同组件的机制。通过 <component :is="...">
语法,开发者可以根据应用状态动态决定渲染哪个组件,实现灵活的内容切换。
1.2 核心语法解析
<component :is="currentComponent"></component>
currentComponent
:可以是已注册的组件名,也可以是组件选项对象- 动态绑定
:is
属性决定当前渲染的组件
1.3 工作原理
Vue 在运行时根据 is
的值决定渲染哪个组件:
- 卸载当前组件实例
- 初始化新组件实例
- 触发相应的生命周期钩子
二、动态组件基础用法
2.1 基本组件切换
<template><div><button @click="current = 'Home'">首页</button><button @click="current = 'About'">关于</button><component :is="current"></component></div>
</template><script>
import Home from './Home.vue'
import About from './About.vue'export default {components: { Home, About },data() {return {current: 'Home'}}
}
</script>
2.2 动态组件类型
类型 | 示例 | 特点 |
---|---|---|
组件名(字符串) | :is="'Home'" | 需全局/局部注册 |
组件选项对象 | :is="HomeComponent" | 直接引用组件对象 |
动态组件名 | :is="dynamicComponentName" | 根据逻辑动态确定组件 |
三、组件切换行为控制
3.1 保持组件状态
默认情况下切换动态组件时,组件的状态不会保留。使用 <keep-alive>
包裹可缓存组件实例:
<keep-alive><component :is="currentComponent"></component>
</keep-alive>
3.2 keep-alive
生命周期
- activated:组件被激活时触发
- deactivated:组件被停用时触发
3.3 缓存策略配置
<keep-alive :include="['Home', 'About']" :exclude="['Admin']" :max="5"><component :is="currentComponent"></component>
</keep-alive>
include
:匹配组件名/组件实例缓存exclude
:排除不缓存的组件max
:最大缓存组件数(LRU策略)
四、动态组件高级模式
4.1 动态组件工厂模式
export default {data() {return {componentMap: {home: HomeComponent,about: AboutComponent