Vue3动态组件实战:5个高级组件切换技巧
1. 基础动态组件
使用component标签实现简单切换:
<script setup>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'
import { ref } from 'vue'
const currentComponent = ref('ComponentA')
</script>
<template>
<button @click="currentComponent = currentComponent === 'ComponentA' ? 'ComponentB' : 'ComponentA'">
切换组件
</button>
<component :is="currentComponent" />
</template>
2. 动态组件传参
向动态组件传递props:
<component
:is="activeComponent"
:title="componentTitle"
:data="componentData"
/>
// 接收组件中
defineProps(['title', 'data'])
3. 组件状态保持
使用KeepAlive保留组件状态:
<KeepAlive>
<component :is="currentComponent" />
</KeepAlive>
// 指定缓存策略
<KeepAlive :max="3">
<component :is="currentComponent" />
</KeepAlive>
4. 异步动态组件
实现组件懒加载:
const AsyncComponent = defineAsyncComponent(() =>
import('./AsyncComponent.vue')
)
// 使用
<component :is="AsyncComponent" />
实现方式 | 优点 | 适用场景 |
---|---|---|
基础动态组件 | 简单直接 | 少量组件切换 |
KeepAlive | 状态保持 | 表单/多步骤流程 |
异步组件 | 性能优化 | 大型应用 |
5. 动态组件工厂
实现动态组件注册系统:
<script setup>
const componentMap = {
'text': defineAsyncComponent(() => import('./TextComponent.vue')),
'image': defineAsyncComponent(() => import('./ImageComponent.vue')),
'video': defineAsyncComponent(() => import('./VideoComponent.vue'))
}
const currentType = ref('text')
</script>
<template>
<component :is="componentMap[currentType]" />
</template>
合理使用动态组件可以创建高度灵活的前端应用,特别适合CMS系统、可视化编辑器和多步骤表单等复杂场景。