当前位置:首页 > VUE

vue 实现动态组件

2026-03-30 06:28:53VUE

Vue 动态组件的实现方法

Vue 中实现动态组件主要通过 component 标签和 is 属性完成,以下为具体实现方式:

使用 component 标签

通过 :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>

动态组件切换

通过方法或计算属性控制当前显示的组件:

vue 实现动态组件

<template>
  <component :is="currentComponent"></component>
  <button @click="toggleComponent">切换组件</button>
</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>
  <component :is="currentComponent"></component>
</keep-alive>

异步组件

结合动态导入实现按需加载:

vue 实现动态组件

components: {
  AsyncComponent: () => import('./AsyncComponent.vue')
}

组件注册方式

全局注册:

Vue.component('GlobalComponent', {...})

局部注册:

export default {
  components: {
    LocalComponent
  }
}

注意事项

  • 组件名称需与注册名称严格匹配(区分大小写)
  • 动态组件切换时会触发生命周期钩子,使用 keep-alive 时可额外触发 activated/deactivated
  • 异步组件需配合 Webpack 等打包工具的代码分割功能使用

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

相关文章

vue实现动态显示布局

vue实现动态显示布局

Vue 实现动态显示布局的方法 动态显示布局通常涉及根据数据或用户交互动态调整页面结构和内容。以下是几种常见的实现方式: 使用 v-if 和 v-show 指令 v-if 和 v-show 都可以控…

组件elementui

组件elementui

ElementUI 简介 ElementUI 是一套基于 Vue.js 的桌面端组件库,由饿了么前端团队开发并开源。它提供了丰富的 UI 组件(如按钮、表单、表格等),适合快速构建企业级中后台产品。…

vue实现tooltips组件

vue实现tooltips组件

实现基础 Tooltip 组件 创建一个名为 Tooltip.vue 的单文件组件,包含模板、样式和逻辑: <template> <div class="tooltip-con…

vue实现水印组件

vue实现水印组件

Vue 水印组件的实现方法 使用Canvas绘制水印 在Vue组件中通过Canvas动态生成水印图案,将其作为背景添加到目标元素上。 <template> <div ref="…

vue实现父子组件

vue实现父子组件

Vue 父子组件通信实现方式 1. 父组件向子组件传递数据(Props) 父组件通过 props 向子组件传递数据,子组件通过 props 接收数据。 父组件模板: <template>…

vue 动态组件实现

vue 动态组件实现

vue 动态组件实现 Vue 的动态组件功能允许根据条件或用户交互动态切换不同的组件,主要通过 <component> 标签和 is 属性实现。 基本用法 通过 is 属性绑定组件名或组…