Vue3 Slots <slot>
In Vue3, slots are a mechanism that allows a parent component to pass content to a child component. You can think of a slot as a reserved "placeholder" in a child component, where the parent component can insert any content. This way, the child component can flexibly display the content passed from the parent without changing its own structure.
Basic Usage of Slots
Default Slot
The default slot is the simplest type of slot. In a child component, you can use<slot>tag to define a default slot. When the parent component uses the child component, it can insert content into this slot.
Example
<template>
<div class="child">
<h3>This is the child component's title</h3>
<slot>Default content</slot>
</div>
</template>
Example
<template>
<ChildComponent>
<p>This is the content passed by the parent component</p>
</ChildComponent>
</template>
In the parent component, we can<ChildComponent>insert content inside the tag, and this content will replace the<slot>tag in the child component. If the parent component does not pass content, the child component will display the<slot>default content inside the tag.
Named Slots
Named slots allow you to define multiple slots in a child component and distinguish them by name. In the parent component, you can use thev-slotdirective to specify which slot to insert content into.
Example
<template>
<div class="child">
<header>
<slot name="header">Default header content</slot>
</header>
<main>
<slot>Default body content</slot>
</main>
<footer>
<slot name="footer">Default footer content</slot>
</footer>
</div>
</template>
Example
<template>
<ChildComponent>
<template v-slot:header>
<h1>Custom header content</h1>
</template>
<p>This is the body content passed by the parent component</p>
<template v-slot:footer>
<p>Custom footer content</p>
</template>
</ChildComponent>
</template>
In the above example, we defined three slots:header、main(default slot) andfooter. The parent component uses thev-slotdirective to insert content into the corresponding slot.
Scoped Slots
Scoped slots allow a child component to pass data to the parent component, and the parent can render content based on this data. This is very useful when you need to customize the rendering logic inside the child component.
Basic Usage
In a child component, you can usev-bindto pass data to the slot. The parent component can then use thev-slotdirective to receive this data.
Example
<template>
<div class="child">
<slot :user="user"></slot>
</div>
</template>
<script>
export default {
data() {
return {
user: { name: 'Alice', age: 25 }
};
}
};
</script>
Example
<template>
<ChildComponent v-slot="{ user }">
<p>User name: {{ user.name }}</p>
<p>User age: {{ user.age }}</p>
</ChildComponent>
</template>
In this example, the child component passes thev-bindwilluserobject to the slot, and the parent component uses thev-slot="{ user }"to receive this object, and renders content based on theuserdata.
Other Extensions
Vue3 Options API