Slots in Vue.js

Slots are tools in Vue.js for creating reusable components.  If you don’t know what Vue components are it will be hard to understand slots. Components are reusable instances of Vue with a name. For example <button-counter>. They accept options as new Vue like data, computed, watch, methods and life cycle hooks. With the release of Vue 2.6 the syntax for slots has became more concise. Slots provide re-usability, new features, readability etc. It allows you to compose your components in a way other than the parent-child relationship. It provides an outlet to place contents in new places. Let’s see an example.

// frame.vue

<template>

  <div class="frame">

    <slot></slot>

  </div>

</template>

Here the wrapper  is div and it creates a stylistic frame around the content. It can be generally used to wrap a frame around any content.

// app.vue

<template>

  <frame><img src="an-image.jpg"></frame>

</template>

Here the frame component refers to the component we have just made. The slot is replacing the slot tag where our content between the opening and closing frame tags will get inserted into the frame.  The default way to use it is shown below.

// frame.vue

<template>

  <div class="frame">

    <slot>This is the default content if nothing gets specified to go here</slot>

  </div>

</template>

There are two types of slots Multiple slots and scoped slots. Scoped slots can pass data or functions to their children. Multiple slots means you can add multiple slots to a component and all but one of them is required to have a name.