首页 文章

是否可以将组件作为道具传递并在Vue中的子组件中使用它?

提问于
浏览
20

在Vue 2.0应用程序中,假设我们有组件A,B和C.

声明,注册和使用B.

是否有可能将C从A传递给B?

像这样的东西:

<template>
  <div class="A">
    <B :child_component="C" />
  </div>
</template>

并以某种方式在B中使用C.

<template>
  <div class="B">
    <C>Something else</C>
  </div>
</template>

动机:我想创建一个在 A 中使用的通用组件 B ,但是从 A 接收它的子 C . 实际上 A 会多次使用 B 传递不同的'C' .

如果这种方法不正确,在Vue中这样做的正确方法是什么?

Answering @Saurabh

而不是作为道具传递,我尝试了B.内部的建议 .

<!-- this is where I Call the dynamic component in B -->

<component :is="child_component"></component>

//this is what I did in B js
components: {
 equip: Equipment
}, 
data () {
 return {
   child_component: 'equip',
   _list: []
 }
}

基本上我试图渲染设备,但动态的方式

我在控制台和空白页面中收到3个错误

[Vue警告]:在/home/victor/projetos/tokaai/public/src/components/EquipmentFormItem.vue渲染组件时出错:未捕获TypeError:无法读取未定义的属性'name'TypeError:无法读取属性'setAttribute'的未定义

显然我做错了什么

2 回答

  • 10

    您可以使用特殊属性 is 来执行此类操作 . 可以在here找到动态组件及其用法的示例 .

    您可以使用相同的挂载点,并使用保留元素在多个组件之间动态切换,并动态绑定到其is属性:

    您的代码如下所示:

    <template>
      <div class="B">
        <component :is="child_component"> Something else</component>
      </div>
    </template>
    
  • 9

    加起来:

    <!-- Component A -->
    <template>
      <div class="A">
        <B>
          <component :is="child_component"></component>
        </B>
      </div>
    </template>
    
    <script>
    import B from './B.vue';
    import Equipment from './Equipment.vue';
    
    export default {
      name: 'A',
      components: { B, Equipment },
      data() {
        return { child_component: 'equipment' };
      }
    };
    </script>
    
    <!-- Component B -->
    <template>
      <div class="B">
        <h1>Some content</h1>
        <slot></slot> <!-- Component C will appear here -->
      </div>
    </template>
    

相关问题