Sobes.tech
Middle

What are slots used for in Vue and how do they work?

sobes.tech AI

Answer from AI

Slots in Vue are used to inject content into components from outside. This allows creating flexible and reusable components.

There are three types of slots:

  • Default Slots: Used for inserting main content.

    <template>
      <div>
        <slot></slot>
      </div>
    </template>
    

    Usage:

    <my-component>
      <p>This content will be inserted into the default slot.</p>
    </my-component>
    
  • Named Slots: Allow inserting content into specific slots within a component, distinguished by name.

    <template>
      <div>
        <slot name="header"></slot>
        <div>Main component content</div>
        <slot name="footer"></slot>
      </div>
    </template>
    

    Usage:

    <my-component>
      <template v-slot:header>
        <h2>Header</h2>
      </template>
      <template v-slot:footer>
        <p>Footer</p>
      </template>
    </my-component>
    

    Shorthand syntax for v-slot:

    <my-component>
      <template #header>
        <h2>Header (shorthand syntax)</h2>
      </template>
    </my-component>
    
  • Scoped Slots: Allow the child component to pass data to the parent component via the slot. The parent can use this data when rendering the slot content.

    <template>
      <ul>
        <li v-for="item in items" :key="item.id">
          <slot :item="item" :index="index"></slot>
        </li>
      </ul>
    </template>
    
    

    Usage:

    <my-list :items="['Apple', 'Banana', 'Orange']">
      <template v-slot:default="slotProps">
        {{ slotProps.index + 1 }}. {{ slotProps.item }}
      </template>
    </my-list>
    
    

    Destructuring slotProps:

    <my-list :items="['Apple', 'Banana', 'Orange']">
      <template v-slot="{ item, index }">
        {{ index + 1 }}. {{ item }} (Destructured)
      </template>
    </my-list>
    

Slots work by creating "places" inside the child component's template, where the parent can insert its own content. During rendering, Vue replaces the <slot> (or <slot name="...">) tag with the content provided by the parent component. In the case of scoped slots, data from the child component is accessible through the slot template's argument object in the parent.