Reputation: 39
I have three component (A, B and C) and I need to pass the component B or C as a property of component A, and the component B will add this component to its template, so in this case, I can pass any component.
Component A
<template>
<div>
<h1>header</h1>
{{ component }}
</div>
</template>
<script>
export default {
name: 'A',
props: {
component: {
required: true,
},
},
};
</script>
Component B
<template>
c
</template>
<script>
export default {
name: 'B',
};
</script>
Component C
<template>
<p>Hello world!</p>
</template>
<script>
export default {
name: 'B',
};
</script>
So, if I pass the component B as a property of component A the result should be:
<h1>header</h1>
<span>this is the content</span>
but if I pass the component C as a property the result should be:
<h1>header</h1>
<p>Hello world!</p>
I tried creating a property in A component and passing but I received undefined:
<template>
<A :component="component"></A>
</template>
...
props: {
component: {
template: '<B></B>',
},
},
Does anyone know how to do it?
UPDATED:
Finally I used the vue's slot. https://v2.vuejs.org/v2/guide/components-slots.htmlUpvotes: 0
Views: 2001
Reputation: 3615
You should be able to do what you want with Vue's "Dynamic Components." You can then pass the name of the component B
or C
as a prop to A
and then use it in the following manner.
<template>
<div>
<h1>header</h1>
<component v-bind:is="dynamicComponent"></component>
</div>
</template>
<script>
export default {
props: ['dynamicComponent'],
}
</script>
The actual syntax is <component v-bind:is="theComponentName"></component>
or with shorthand v-bind <component :is="theComponentName"></component>
For more see the docs here: https://v2.vuejs.org/v2/guide/components.html#Dynamic-Components
Upvotes: 1