yousuf
yousuf

Reputation: 41

How to use only one named slot in the component?

`I have a component which holds different slots for example:

header slot, main slot and footer slot

base-layout.vue

<template>
  <div class="container">
    <header>
      <slot name="header"></slot>
    </header>
    <main>
      <slot></slot>
    </main>
    <footer>
      <slot name="footer"></slot>
    </footer>
  </div>
</template>

I have another component(Main) which is used to render to the screen.

<template>
  <base-layout>
    <template v-slot:header>
      <h2>Hello world</h2>
    </template>
  </base-layout>
</template>

Inside Main component I need only to use header slot, instead when I try to do so all the other slots are also getting picked up

Upvotes: 3

Views: 507

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You could use conditional rendering to render them if the respective slot is provided :

<template>
  <div class="container">
    <header v-if="$slots.header">
      <slot name="header"></slot>
    </header>
    <main v-if="$slots.default">
      <slot></slot>
    </main>
    <footer v-if="$slots.footer">
      <slot name="footer"></slot>
    </footer>
  </div>
</template>

or just do :

<template>
  <div class="container">
   
      <slot name="header"></slot>
  
      <slot></slot>
      <slot name="footer"></slot>

  </div>
</template>

the in parent provide the wrapping elements like header, main and footer

<template>
  <base-layout>
    <template v-slot:header>
        <header><h2>Hello world</h2></header>
    </template>
  </base-layout>
</template

Upvotes: 7

Related Questions