当前位置:首页 > VUE

vue 动态组件实现

2026-02-17 17:11:30VUE

Vue 动态组件实现方法

动态组件是 Vue 中通过 <component> 标签结合 is 属性实现组件动态切换的功能,常用于选项卡、多步骤表单等场景。

基本语法

使用 <component :is="currentComponent"> 绑定动态组件,通过改变 currentComponent 的值切换组件:

vue 动态组件实现

<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 实现按需加载,优化性能:

vue 动态组件实现

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: 前缀)

标签: 组件动态
分享给朋友:

相关文章

vue动态实现select

vue动态实现select

vue动态实现select的方法 使用v-for动态渲染选项 通过v-for指令可以动态生成select的option选项。将选项数据存储在data中,利用v-for遍历数据生成下拉列表。 <…

uniapp如何将底部导航组件化

uniapp如何将底部导航组件化

在 uniapp 中将底部导航组件化 将底部导航组件化可以提高代码复用性和维护性。以下是具体实现方法: 创建自定义底部导航组件 新建一个组件文件,例如 tab-bar.vue,放置在 compon…

vue动态表格实现

vue动态表格实现

Vue动态表格实现方法 使用v-for指令渲染动态数据 通过v-for指令可以循环遍历数组数据生成表格行,数据变化时表格自动更新。示例代码: <template> <table…

vue实现动态表单

vue实现动态表单

Vue 动态表单实现方法 使用 v-for 动态渲染表单字段 通过遍历数组动态生成表单项,数据驱动视图变化。表单字段配置可存储在数组中,修改数组即可实现表单动态更新。 <template>…

react如何刷新组件

react如何刷新组件

刷新 React 组件的常见方法 使用状态更新触发重新渲染 通过修改组件的状态(state),React 会自动触发重新渲染。例如: const [count, setCount] = useSta…

vue实现树形组件

vue实现树形组件

实现树形组件的基本思路 在Vue中实现树形组件通常涉及递归组件和动态数据渲染。核心是通过组件自身调用自身,逐层渲染嵌套的节点数据。 定义树形数据结构 树形数据通常是一个包含children属性的对象…