icon-dark icon-light

Slots in Vue

Slots in Vue

Let’s learn how to use slots in Vue.js today.

Slots are a powerful tool for creating reusable or SFC(Single File Component) in Vue. Slots give you an outlet to place content in new places or make components more generic.

Here’s a simple slot example:

simpleComponent.vue

<div>
  <h2>I'm a title</h2>
  <slot>Only displayed if no slot content</slot>
</div>

Now let’s use this component in main.vue file

<simple-component>
  <p>This will go in the slot</p>
</simple-component>

The output would be:

I'm title
This will go in the slot

If the slot content is not added in main.vue the output would be:

I'm title
Only displayed if no slot content

If no Content is provided, it would fallback to default slot content if there is any mentioned in simpleComponent as in this case.


Multiple Slots

Now let’s look at a scenario where there are different designs and how multiple slots utilise them.

appLayout.vue

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

main.vue

<app-layout>
  <h1 slot="header">Page title</h1>
  <p>the main content.</p>
  <p slot="footer">Contact info</p>
</app-layout>

Now if you see, the header value is mentioned for slot value for h1 tag and value footer for slot value p tag. And default slot will hold the p tag with “the main content” content.

Hope you found this short article useful. If so hit the 👍🏻❤️

Loading...