Skip to content
Advertisement

How to render component children at parent

I’m familiar with ReactJS, but not with VueJS.

Where can I place the component children at the parent component. I have this example in ReactJS, how can I create the same using VueJs:

function FancyBorder(props) {
  return (
    <div className={'FancyBorder FancyBorder-' + props.color}>
      {props.children}
    </div>
  );
}

function WelcomeDialog() {
  return (
    <FancyBorder color="blue">
      <h1 className="Dialog-title">
        Welcome
      </h1>
      <p className="Dialog-message">
        Thank you for visiting our spacecraft!
      </p>
    </FancyBorder>
  );
}

What is the {props.children} in VueJS ??

Answer

The Vue analogy to the React “children” concept is the slots.

https://v2.vuejs.org/v2/guide/components.html#Content-Distribution-with-Slots https://v2.vuejs.org/v2/guide/components-slots.html

Slots can be used like:

// FancyBorder.vue

<div class="FancyBorder">
    <slot/>
</div>

// App.vue

<FancyBorder>
    Contents!
</FancyBorder>

Vue slots also have an advantage over the React children, as you can have multiple “groups” of elements, using named slots, this can make the code less reliant on “magic” classnames:

// FancyBorder.vue

<div class="FancyBorder">
    <h1 className="Dialog-title">
        <slot name="header"></slot>
    </h1>
    <slot/>
</div>

// App.vue

<FancyBorder>
    <template slot="header">
        Header
    </template>
    Contents!
</FancyBorder>
Advertisement