是否可以将组件作为道具传递并在 Vue 的子组件中使用它? [英] Is it possible to pass a component as props and use it in a child Component in Vue?
问题描述
在 Vue 2.0 应用程序中,假设我们有组件 A、B 和 C.
A 声明、注册和使用 B
是否可以将 C 从 A 传递到 B?
像这样:
<div class="A"><B :child_component=C";/>
模板>
并以某种方式在 B 中使用 C.
<div class="B"><C>别的东西</C>
模板>
动机:我想创建一个通用组件B
,用于A
,但从A
接收它的子C代码>.实际上
A
会多次使用 B
并将不同的 'C' 传递给它.
如果这种方法不正确,那么在 Vue 中正确的做法是什么?
回答@Saurabh
我没有将其作为道具传递,而是尝试了 B 中的建议.
<!-- 这是我在 B 中调用动态组件的地方 --><component :is="child_component"></component>//这就是我在B js中所做的成分: {装备:装备},数据 () {返回 {child_component: '装备',_列表: []}}
基本上我正在尝试渲染设备,但以动态方式
我在控制台和空白页面中收到 3 个错误
<块引用>[Vue 警告]:在/home/victor/projetos/tokaai/public/src/components/EquipmentFormItem.vue 渲染组件时出错:
未捕获的类型错误:无法读取未定义的属性名称"
TypeError: 无法读取未定义的属性setAttribute"
显然我做错了什么
你可以使用特殊属性 is
来做这种事情.动态组件示例及其用法可以在此处找到.
您可以使用相同的挂载点并使用保留元素在多个组件之间动态切换并动态绑定到其 is 属性:
您的代码如下所示:
<div class="B"><组件:is="child_component">别的东西</component>
模板>
In a Vue 2.0 app, let's say we have components A, B and C.
A declares, registers and uses B
Is it possible to pass C from A to B?
Something like this:
<template>
<div class="A">
<B :child_component="C" />
</div>
</template>
And use C in B somehow.
<template>
<div class="B">
<C>Something else</C>
</div>
</template>
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.
If this approach is not correct, what is the proper way of doing it in Vue?
Answering @Saurabh
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
I get 3 errors in console and a blank page
[Vue warn]: Error when rendering component at /home/victor/projetos/tokaai/public/src/components/EquipmentFormItem.vue:
Uncaught TypeError: Cannot read property 'name' of undefined
TypeError: Cannot read property 'setAttribute' of undefined
Apparently I'm doing something wrong
You can use special attribute is
for doing this kind of thing. Example of dynamic component and it's usage can be found here.
You can use the same mount point and dynamically switch between multiple components using the reserved element and dynamically bind to its is attribute:
Your code will look like following:
<template>
<div class="B">
<component :is="child_component"> Something else</component>
</div>
</template>
这篇关于是否可以将组件作为道具传递并在 Vue 的子组件中使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!