Skip to content

Slot in Vue js

Slot in Vue js

1. Overview

In this article, we will learn about Slot in Vue js. To learn more about Vue js, refer to our articles.

2. Slot in Vue Js

A slot allows a parent component to define an injectable slice of HTML and inject or place it somewhere in a child component.

So slots are optimal when we want the parent component to customize some bit of HTML that is going to be rendered within the child.

2.1. Slot vs props

Vue components can accept props, which can be JavaScript values of any type, whereas a Slot can help to pass template content \ fragment to the child component and let the child component render the fragment within its own template.

It is just like props as they both allow a parent component to pass something down to a child component. Props exist for passing down data i.e., JavaScript values of any type such as strings, numbers, boolean, arrays, and objects.

In comparison, slots allow a parent component to pass down HTML – a markup or elements to render within the body of the child component.

A Slot is an open place where the parent component can provide HTML to inject while still keeping the rest of the content of the view component.

3. A Vue js slot example

For example, we may refer to the child component <FancyButton> in our parent component App.vue that supports usage like this:

<script>
import FancyButton from './FancyButton.vue'
  
export default {
  components: { FancyButton }
}
</script>

<template>
  <FancyButton>
    Click me <!-- slot content -->
 	</FancyButton>
</template>

The template of child component <FancyButton> looks like this:

<template>
  <button>
  	<slot/> <!-- slot outlet -->
  </button>
</template>

The <FancyButton> renders the outer <button> and its style, while the parent component provides the inner content. The <slot> element is a slot outlet that displays the content provided by the parent.

Slot in vue js
Final rendered DOM – Chrome Inspect

3.1. Slot with multiple elements

Slot content is not just limited to text. It can be any valid template content. We can pass in multiple elements or even other components:

Slot with multiple content
Slot with multiple DOM elements

4. Conclusion

To sum up, we have learned Slot in Vue js. By using slots, we can make our child components more flexible and reusable. We can use it in different places with different inner content, but all with the same styling.

1 thought on “Slot in Vue js”

  1. Pingback: Named slots in Vue js - TedBlob

Leave a Reply

Your email address will not be published. Required fields are marked *