Search code examples
vue.jscomponentsvuejs2vue-component

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?


Solution

  • 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.