当前位置:首页 > 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轮播组件实现

vue轮播组件实现

Vue 轮播组件实现方法 使用第三方库(如 Swiper) 安装 Swiper 库: npm install swiper 在 Vue 组件中引入 Swiper: <template&g…

vue动态组件实现

vue动态组件实现

Vue 动态组件实现方法 使用 component 标签与 is 属性 通过 Vue 内置的 <component> 标签和 is 属性实现动态组件切换。is 的值可以是已注册的组件名或导…

vue实现倒计时组件

vue实现倒计时组件

Vue 倒计时组件实现 核心思路 通过 setInterval 或 setTimeout 实现时间递减,结合 Vue 的响应式数据更新 UI。需注意组件销毁时清除定时器。 基础实现方案 模板部分…

vue VUE实现日历组件功能

vue VUE实现日历组件功能

Vue 日历组件实现方法 基础日历结构 使用Vue的模板语法构建日历的HTML结构,通常包含头部(年月显示、切换按钮)和日历表格(星期标题和日期格子)。 <template> <…

vue实现组件跟随

vue实现组件跟随

Vue 实现组件跟随效果 实现组件跟随效果通常需要监听鼠标或触摸事件,动态更新组件位置。以下是几种常见实现方式: 使用鼠标事件绑定 <template> <div class…

vue动态组件实现

vue动态组件实现

动态组件的基本用法 在Vue中,动态组件通过<component>标签和is属性实现。is属性可以绑定组件名称或组件选项对象,实现动态切换。 <template> <…