是否可以将组件作为道具传递并在Vue中的子组件中使用它? [英] Is it possible to pass a component as props and use it in a child Component in Vue?

查看:68
本文介绍了是否可以将组件作为道具传递并在Vue中的子组件中使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In a Vue 2.0 app, let's say we have components A, B and C.

A声明,注册并使用B

A declares, registers and uses B

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

Is it possible to pass C from A to B?

这样的事情:

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

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

And use C in B somehow.

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

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

The motivation: I want to create a generic component B that is used in A but receives from A its child C. Actually A will use B several times passing different 'C's to it.

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

If this approach is not correct, what is the proper way of doing it in Vue?

回答@Saurabh

我尝试了B内的建议,而不是传递道具。

Instead of passing as props, I tried the suggestion inside 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: []
 }
}

基本上我正在尝试渲染设备,但动态方式

Basically I'm trying to render Equipment, but the dynamic way

我在控制台和空白页面中出现3个错误

I get 3 errors in console and a blank page


[Vue警告]:在/home/victor/projetos/tokaai/public/src/components/EquipmentFormItem.vue呈现组件时出错:

[Vue warn]: Error when rendering component at /home/victor/projetos/tokaai/public/src/components/EquipmentFormItem.vue:

未捕获的TypeError:无法读取未定义的属性'name'

Uncaught TypeError: Cannot read property 'name' of undefined

TypeError:无法读取未定义的属性'setAttribute'

TypeError: Cannot read property 'setAttribute' of undefined

显然我做错了什么

推荐答案

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

You can use special attribute is for doing this kind of thing. Example of dynamic component and it's usage can be found here.


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

You can use the same mount point and dynamically switch between multiple components using the reserved element and dynamically bind to its is attribute:

您的代码如下所示:

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

这篇关于是否可以将组件作为道具传递并在Vue中的子组件中使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆