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.
//Vue version 2.xh(LayoutComponent, [h('div', { slot: 'header' }, this.header),h('div', { slot: 'content' }, this.content)])
Scoped slots could be referenced using the following syntax:
// Vue version 2.xthis.$scopedSlots.header
In Vue 3, slots are defined as children of the current node, where the child parameter is an object:
// Vue version 3.xh(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:
// Vue version 2.xthis.$scopedSlots.header// Vue version 3.xthis.$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";
-
A
Vueinstance is created in theunified-slots.jsfile that renders theParentcomponent, imported from theunified-slots-parent.vuefile. -
The
Parentcomponent renders theChildcomponent in therendermethod. -
The
Childcomponent receives two slots,headerandcontent. Both receive states defined in thedata(){} function. -
The
Child...