当前位置:首页 > VUE

vue动态组件实现

2026-01-08 14:31:48VUE

Vue 动态组件实现方法

使用 component 标签与 is 属性

通过 Vue 内置的 <component> 标签和 is 属性实现动态组件切换。is 的值可以是已注册的组件名或导入的组件对象。

<template>
  <component :is="currentComponent"></component>
</template>

<script>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'

export default {
  data() {
    return {
      currentComponent: 'ComponentA'
    }
  },
  components: {
    ComponentA,
    ComponentB
  }
}
</script>

动态切换组件逻辑

通过方法或计算属性控制 currentComponent 的切换,结合按钮或事件触发。

vue动态组件实现

<template>
  <button @click="toggleComponent">切换组件</button>
  <component :is="currentComponent"></component>
</template>

<script>
export default {
  data() {
    return {
      showA: true
    }
  },
  computed: {
    currentComponent() {
      return this.showA ? 'ComponentA' : 'ComponentB'
    }
  },
  methods: {
    toggleComponent() {
      this.showA = !this.showA
    }
  }
}
</script>

保持组件状态(keep-alive

<keep-alive> 包裹动态组件可保留其状态,避免重复渲染。

vue动态组件实现

<template>
  <keep-alive>
    <component :is="currentComponent"></component>
  </keep-alive>
</template>

动态加载异步组件

结合 defineAsyncComponent 实现按需加载,优化性能。

import { defineAsyncComponent } from 'vue'

const AsyncComponent = defineAsyncComponent(() =>
  import('./AsyncComponent.vue')
)

export default {
  components: {
    AsyncComponent
  }
}

传递 Props 和监听事件

动态组件仍可正常接收 Props 和触发事件。

<template>
  <component 
    :is="currentComponent" 
    :propName="value"
    @customEvent="handleEvent"
  ></component>
</template>

适用场景

  • 标签页切换
  • 条件渲染不同UI模块
  • 根据权限显示不同组件
  • 动态表单字段渲染

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

相关文章

vue轮播组件实现

vue轮播组件实现

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

vue radio组件实现

vue radio组件实现

Vue Radio 组件实现 在 Vue 中实现 Radio 组件可以通过原生 HTML 的 <input type="radio"> 结合 Vue 的响应式特性,或者使用第三方 UI 库…

vue实现tooltips组件

vue实现tooltips组件

Vue实现Tooltips组件的方法 基础实现:使用Vue指令 创建一个自定义指令v-tooltip,通过鼠标事件触发提示框的显示与隐藏。 Vue.directive('tooltip', {…

vue 实现组件刷新

vue 实现组件刷新

实现组件刷新的方法 在Vue中,组件刷新通常指重新渲染组件或重置组件状态。以下是几种常见的实现方式: 使用v-if控制渲染 通过v-if指令可以销毁并重新创建组件: <template&…

vue动态实现select

vue动态实现select

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

vue实现动态隐藏

vue实现动态隐藏

动态隐藏的实现方法 在Vue中实现动态隐藏可以通过多种方式,常见的有条件渲染、动态绑定样式或类名。以下是几种具体实现方法: 使用v-if或v-show指令 <template> &…