vue 动态组件实现
Vue 动态组件实现方法
动态组件是 Vue 中通过 <component> 标签结合 is 属性实现组件动态切换的功能,常用于选项卡、多步骤表单等场景。
基本语法
使用 <component :is="currentComponent"> 绑定动态组件,通过改变 currentComponent 的值切换组件:

<template>
<component :is="currentComponent"></component>
<button @click="currentComponent = 'ComponentA'">显示A</button>
<button @click="currentComponent = 'ComponentB'">显示B</button>
</template>
<script>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'
export default {
components: { ComponentA, ComponentB },
data() {
return {
currentComponent: 'ComponentA'
}
}
}
</script>
动态组件缓存
默认情况下切换组件会销毁旧组件实例,使用 <keep-alive> 包裹可缓存组件状态:
<keep-alive>
<component :is="currentComponent"></component>
</keep-alive>
动态导入异步组件
结合 defineAsyncComponent 实现按需加载,优化性能:

const AsyncComponent = defineAsyncComponent(() =>
import('./AsyncComponent.vue')
)
组件切换过渡效果
通过 <transition> 添加动画效果:
<transition name="fade" mode="out-in">
<component :is="currentComponent"></component>
</transition>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
传递 Props 和事件
动态组件支持常规的 props 和事件绑定:
<component
:is="currentComponent"
:prop1="value1"
@custom-event="handleEvent"
></component>
注意事项
- 组件名需与注册名称完全匹配(区分大小写)
- 动态组件切换会触发生命周期钩子,使用
keep-alive时会触发activated/deactivated - 在 Vue 3 中,
is属性也可用于原生 HTML 元素(需添加vue:前缀)





