Dioralop
Dioralop

Reputation: 165

How to define a slot in a Vue.js template when using render function?

When defining a slot in a Vue.js component template using regular old HTML, it's as simple as this:

<div>
    <h1>Hello, I am a template!</h1>
    <slot name="my_slot"></slot>
</div>

And it can be activated like so when using the template in your page:

<my-template>
    <template slot="my_slot">
        <p>Slot content.</p>
    </template>
</my-template>

Which should output something like:

<div>
    <h1>Hello, I am a template!</h1>
    <p>Slot content.</p>
</div>

However, my situation requires that I define my component template using the render function which means the template DOM needs to be set up using nested calls to the createElement function. So my original template definition would now look something like this:

h('div', {}, [
    h('h1', {
        domProps:{
            innerHTML: "Hello, I am a template!"
        }
    }, []),
    h('slot', {
        attrs:{
            name: "my_slot"
        }
    }, [])
])

However this doesn't work for me. I'm assuming it's because 'slot' isn't a valid html tag but I can't seem to find any clear answer on this specific subject. How can I correctly define slots in a Vue.js component template when using the render function?

Upvotes: 6

Views: 7346

Answers (2)

Stephen Thomas
Stephen Thomas

Reputation: 14053

From the documentation

h('div', {}, [
    h('h1', {
        domProps:{
            innerHTML: "Hello, I am a template!"
        }
    }, []),
    this.$slots.my_slot
])

Upvotes: 5

Yeachan
Yeachan

Reputation: 69

h('div', {}, [
    h('h1', {
        domProps:{
            innerHTML: "Hello, I am a template!"
        }
    }, []),
    h('div', {
        slot: 'my_slot'
    }, [])
])

and it works.

Upvotes: 1

Related Questions