vue给components动态添加组件

在Vue中,可以使用v-bind指令来动态地将组件添加到其他组件上。

首先,需要定义一个包含所有可能的子组件的数组或对象。然后,通过计算属性(computed property)根据条件选择要显示的组件。最后,使用<component>元素并结合is特性来动态地切换不同的组件。

javascript 复制代码
<!-- ParentComponent.vue -->
<template>
  <div>
    <!-- 根据条件选择要显示的组件 -->
    <component :is="currentComponent"></component>
    
    <!-- 按钮点击事件触发切换组件 -->
    <button @click="toggleComponent">Toggle Component</button>
  </div>
</template>

<script>
import ChildComponent1 from './ChildComponent1.vue'; // 导入第一个子组件
import ChildComponent2 from './ChildComponent2.vue'; // 导入第二个子组件

export default {
  components: {
    ChildComponent1,
    ChildComponent2
  },
  
  data() {
    return {
      currentComponent: 'ChildComponent1' // 默认显示第一个子组件
    };
  },
  
  methods: {
    toggleComponent() {
      this.currentComponent = (this.currentComponent === 'ChildComponent1') ? 'ChildComponent2' : 'ChildComponent1';
    }
  }
};
</script>

这样就可以根据需求动态地向ParentComponent中添加不同的子组件了。

相关推荐
tryCbest1 天前
Vue3——第 22 篇:Pinia——新一代状态管理(上)
前端·javascript·vue.js
bai2731 天前
"👨‍👩‍👧‍👦" 的 length 是 11:我把自己写的字数统计脚本拖出来审了一遍
前端·javascript
zhanlang02171 天前
HTML 零基础入门到企业实战【第八章 8.5】画布 canvas、SVG 矢量图形基础入门
前端·html
星云_byto1 天前
CSS面试题
前端·css
zhanlang02171 天前
HTML 零基础入门到企业实战全套教程【连载 8.4】HTML5 新增表单属性与表单控件
前端·html·html5
科研邪修法1 天前
PDF新增页面文字与文本批注怎么区分?以双版本培训讲义为例
前端·css·pdf
Lanwarf-前端开发1 天前
Vue3 + Canvas/WebGL 雷达扫描可视化实战:PPI、RHI、VOL、SVOL 四种模式原理与实现
前端·javascript·vue.js·webgl
FRing031 天前
vue3干货总结2(vue3生命周期、父子通信、模版引用、provide和inject)
开发语言·前端·vue.js·vue3
锋行天下2 天前
langgraph 全栈项目(三)
前端·人工智能·后端
锋行天下2 天前
langgraph 全栈项目(二)
前端·人工智能·后端