Banning Stuckey
Banning Stuckey

Reputation: 575

Vuejs Slot Parent Child

How do I get these 2 components to work together?

Vue.component('parent', {
    template: ''+
        '<slot name="foo"></slot>'+
    ''
});

Vue.component('child', {
    template: ''+
        '<div slot="foo">bar</div>'+
    ''
});

I thought I could do something like this but it didn't appear to work

Vue.component('parent', {
    components: [
        'child'
    ],
    template: ''+
        '<slot name="foo"></slot>'+
    ''
});

Here is a JS Fiddle https://jsfiddle.net/3fjmLL52/

Upvotes: 2

Views: 3924

Answers (1)

Bert
Bert

Reputation: 82499

If you want the child to be rendered in the parent, the template would look like this:

<div id="app">
    <main>
        <parent>
          <child slot="foo"></child>
        </parent>
    </main>
</div>

You also can remove the slot="foo" from the child template.

Vue.component('child', {
    template: `<div>bar</div>`
});

Vue.component('parent', {
    template: `
    <div>
      <slot name="foo">Default</slot>
      <h1><slot name="bar">Header</slot>
 	  </div>`
});

Vue.component('child', {
    template: '' +
        '<div>bar</div>' +
	''
});

new Vue({
    el: '#app'
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="app">
    <main>
        <parent>
          <child slot="foo"></child>
          <span slot="bar">Header Content</span>
        </parent>
    </main>
</div>

Upvotes: 2

Related Questions