## Vue3 v-slot Directive
The `v-slot` directive is used to define named slots or scoped slots in Vue 3. It is the core mechanism for distributing content between parent and child components, allowing you to build highly reusable and flexible components.
---
## Technical Overview
The `v-slot` directive is used to provide content to a slot or to receive props passed from a child component's slot.
* **Shorthand**: `#` (e.g., `v-slot:header` can be written as `#header`)
* **Expected Value**: A JavaScript expression (optional, only required when receiving slot props)
* **Target Elements**: `
` or components (under specific conditions)
* **Primary Use Cases**: Named slots and Scoped slots
---
## Basic Usage
### 1. Named Slots
By default, if a `` element does not have a `name` attribute, it implicitly has the name `"default"`. When you want to target specific slots in a component with multiple slot outlets, you use named slots.
```html
Page Title
Main content area.
Footer information.
```
### 2. Shorthand Syntax
Like `v-on` (`@`) and `v-bind` (`:`), `v-slot` has a dedicated shorthand: the hash symbol (`#`).
```html
Title
Title
```
---
## Scoped Slots
Scoped slots allow a child component to pass data (props) back up to the parent component's slot content. This is incredibly useful when the parent needs to customize the layout of the data, but the child component owns the data state.
### Example: Passing Data from Child to Parent
#### Parent Component (`App.vue`)
```html
Username: {{ slotProps.user.name }}
```
#### Child Component (`CurrentUser.vue`)
```html
```
---
## Advanced Usage & Best Practices
### 1. Destructuring Slot Props
Instead of accessing properties through a single object (like `slotProps.user`), you can use ES6 destructuring directly inside the `v-slot` directive value.
```html
Username: {{ user.name }}
Username: {{ person.name }} (Status: {{ fallback }})
```
### 2. Combining Named and Scoped Slots
When using both named slots and scoped slots together, append the slot name after the shorthand `#` or `v-slot:` and assign the slot props to it.
```html
| {{ item.id }} |
{{ item.name }} |
```
### 3. Dynamic Slot Names
You can use dynamic arguments with `v-slot` to bind to a slot name determined at runtime.
```html
Dynamic Content
```
---
## Key Considerations
1. **Template Requirement**: `v-slot` can only be applied to `` tags in almost all scenarios. The only exception is when the component *only* has a default slot. In that case, `v-slot` can be applied directly to the component tag.
2. **Avoid Mixing Syntaxes**: Do not mix the default slot shorthand on the component tag with named slots inside `` tags. This can lead to scope ambiguity. Always use explicit `` tags if you have multiple slots.
3. **Performance**: Scoped slots in Vue 3 are compiled into functions. This means child components containing scoped slots can be updated independently of the parent, resulting in better performance compared to Vue 2.