Skip to content
Advertisement

print Component B inside component A – vue.js

Using Vue.js, How to create componentA that gets componentB as a prop, and print it inside of it?

example:

index.vue

JavaScript

componentA.vue

JavaScript

Advertisement

Answer

There are some issues to your implementation:

  1. You have gotten the scope wrong: componentPlaceHolder lives in the parent scope, not in that of component A. Read: Compilation Scope.

  2. Use :is (i.e. v-bind: is) for dynamic component binding. The data bound should reference the key of the component.

  3. Since you are nested additional components in another component in the same context, that means you have to interweave the content. This is done by using slots, declared in <component-a>.

  4. Avoid using case-sensitive DOM elements, use kebab case instead, i.e. <component-a> instead of <componentA>, since HTML elements are case-insensitive (<componentA> and <componenta> will be treated the same).

Here is the updated code:

JavaScript

And then in your componentA.vue:

JavaScript

Proof-of-concept example

If in doubt, here is a live proof-of-concept example:

JavaScript
JavaScript

Footnote:

The VueJS readme is exceptionally composed, and I suggest here are some things that you can read up on that is very relevant to your use case:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement