Vue3 v-slot Directive

Vue3 内置指令Vue3 Built-in Directives


v-slotThe directive is used to denote named slots or scoped slots, for content distribution between components.


Basic Description

v-slotThe directive is used to provide content for slots or receive props passed by slots. It is the core method for implementing component content distribution in Vue.

  • Shorthand: #
  • Expected TypeJavaScript expression (optional, only needed when receiving props)
  • FunctionDenotes named slots or scoped slots.

Basic Usage

1. Named Slots

Example

<template>
  <base-layout>
    <template v-slot:header>
      <h1>Page Title</h1>
    </template>
    <template v-slot:default>
      <p>Main Content Area</p>
    </template>
    <template v-slot:footer>
      <p>Footer Information</p>
    </template>
  </base-layout>
</template>

2. Shorthand Form

Example

<!-- Equivalent -->
<template v-slot:header>Title</template>
<template #header>Title</template>

3. Scoped Slots

Scoped slots allow child components to pass data to parent components:

Example

<!-- Parent Component -->
<template>
  <current-user v-slot="slotProps">
    <p>Username: {{ slotProps.user.name }}</p>
  </current-user>
</template>

<script>
export default {
  components: { CurrentUser }
}
</script>

<!-- Child Component CurrentUser.vue -->
<template>
  <slot :user="currentUser"></slot>
</template>

<script>
export default {
  data() {
    return {
currentUser: { name: 'Zhang San' }
    }
  }
}
</script>

Vue3 内置指令Vue3 Built-in Directives

Other Extensions