Vue3 Slots
In Vue 3, a slot is a mechanism that allows a parent component to pass content to a child component. You can think of a slot as a "placeholder" reserved in the child component, into which the parent can insert arbitrary content. This way, the child component can flexibly display the parent-passed content without changing its own structure.
Basic Usage of Slots
Default Slot
The default slot is the simplest slot type. In the child component, you can use the tag to define a default slot. When using the child component, the parent can insert content into this slot.
Example
This is the child component's title
Default content
Example
This is the content passed by the parent component
In the parent component, we can insert content inside the tag; this content will replace the tag in the child component. If the parent does not pass content, the child component displays the default content inside the tag.
Named Slots
Named slots allow you to define multiple slots in the child component and distinguish them by name. In the parent component, you can use the v-slot directive to specify which slot to insert content into.
Example
Default header content
Default body content
Example
Custom header content
This is the body content passed by the parent component
Custom footer content
In the example above, we defined three slots:header, main(the default slot) and footer. The parent component inserts content into the corresponding slots via the v-slot directive.
Scoped Slots
Scoped slots allow the child component to pass data to the parent component, which can then render content based on that data. This is very useful when you need to customize the child component's internal rendering logic.
Basic Usage
In the child component, you can pass data to the slot via v-bind . The parent component can receive this data via the v-slot directive.
Example
Example
User name: {{ user.name }}
User age: {{ user.age }}
In this example, the child component passes the v-bind data to the child component via user object to the slot, and the parent component receives this object via v-slot="{ user }" and renders content based on the user data.
Vue3 Options API