...

/

Unified Slots and createElement

Unified Slots and createElement

Learn how slots and the createElement function are treated differently in Vue 2 and Vue 3.

We'll cover the following...

Unified slots

Slots and scoped slots were unified in Vue 3. The $scopedSlots property has been removed from Vue components. Instead, the $slots property exposes slots as functions. In Vue 2, slots were defined using the slot data property when using a render function.

Press + to interact
//Vue version 2.x
h(LayoutComponent, [
h('div', { slot: 'header' }, this.header),
h('div', { slot: 'content' }, this.content)
])

Scoped slots could be referenced using the following syntax:

Press + to interact
// Vue version 2.x
this.$scopedSlots.header

In Vue 3, slots are defined as children of the current node, where the child parameter is an object:

Press + to interact
// Vue version 3.x
h(LayoutComponent, {}, {
header: () => h('div', this.header),
content: () => h('div', this.content)
})

Thus, as mentioned previously, slot nodes can be accessed using a method exposed on the this.$slots property:

Press + to interact
// Vue version 2.x
this.$scopedSlots.header
// Vue version 3.x
this.$slots.header()

Run the following code and have look at the unified slots example in Vue 2:

Note: The code below may take a while to run. When the server starts, go to the app URL to see the output.

import "./examples/unified-slots/unified-slots";
Unified slots example in Vue 2
  • A Vue instance is created in the unified-slots.js file that renders the Parent component, imported from the unified-slots-parent.vue file.

  • The Parent component renders the Child component in the render method.

  • The Child component receives two slots, header and content. Both receive states ...