Search⌘ K
AI Features

Unified Slots and createElement

Explore how Vue 3 changes slots by unifying slots and scoped slots into a single $slots property with functions. Learn the updated usage of the createElement function (h), now imported from Vue, and the need for resolveComponent to render components. Understand these render function updates and migration strategies from Vue 2 to Vue 3 to create modern Vue applications.

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.

Javascript (babel-node)
//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:

Javascript (babel-node)
// 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:

Javascript (babel-node)
// 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:

Javascript (babel-node)
// 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 defined in the data() {} function.

  • The Child ...