Victor Ferreira
Victor Ferreira

Reputation: 6449

How do we create nested Vue Components passing other elements as their children

In React I would do something like this:

//ParentComponent.js
(<div>
  {this.props.children}
</div>)

//ChildComponent.js
(<div>
  I'm the child!
</div>)

//App.js
import ParentComponent
import ChildComponent

<ParentComponent>
  <ChildComponent />
  <span>Other element</span>
</ParentComponent>

I understand they are different things, but how could I do something like this in Vue? I want to pass ChildElement in ParentComponent's content, and in ParentComponent I must be able to put its content somewhere.

What is the closest to this idea?

Upvotes: 3

Views: 1870

Answers (1)

Bert
Bert

Reputation: 82459

You would do that using slots.

Vue.component("parent",{
  template:"<div><h1>I'm the parent component</h1><slot></slot></div>",
})

Vue.component("child", {
  template: "<div><h2>I'm the child component</h2></div>"
})

new Vue({
  el:"#app"
})

<div id="app">
  <parent>
    <child></child>
  </parent>
</div>

Example.

Upvotes: 7

Related Questions