Slot Vue Js

  1. Correct way to pass props to all children through slot-scope in Vue.js. How to DRY use a Vue.js component with multiple props and slots. Passing slot into slot.
  2. In the previous post we introduced the Vue.js component model and saw how to pass data to child components via props and how components can emit events up their parents. In this chapter we focus on slots which give your components even more flexibility by injecting content into child components.
  3. Vue.js implements a content distribution API that is modeled after the current Web Components spec draft, using the special slot element to serve as distribution outlets for the original content. Compilation Scope.
bySai gowtham

Vue.js - The Progressive JavaScript Framework. En este ejemplo, hemos elegido nombrar al objeto que contiene todos nuestras propiedades del slot “slotProps”, pero puede usar el nombre que prefiera.

In this tutorial, we will learn about how to use the slots in vue.js with the help of examples.

What are Slots?

Slots helps us to pass the data between opening and closing component tags.

In vue.js props are used to pass the data to its child components, but it is hard to pass when we have a complex code. In such cases slots can be used.

Let’s create a new component called Post by adding the <slot> element.

Now, if we pass any content between the Post component opening and closing tags that are rendered in the place of <slot></slot> element.

Output:

Named Slots

Sometimes, we need to pass the data to a specific places in such cases named slots can be used.

Vue.js Slot Activator

The named slots can be created by adding a name attribute to the <slot> element.

Vue.js Slot V-if

To pass the content to the named slots we need to use v-slot directive on template providing slot name as v-slot argument.

Vue

Fallback data

In some cases, we can use fallback data (aka default) when data is not passed to a slot.

For example:

In the above component, we have added a Submit text inside a slot element.

Now, If we use a my-button component without passing any data we can seethe fallback data Submit text is rendered inside the button.

Slot In Vue Js

Output of rendered html:

But, if we pass data to the my-button component fallback data is replaced.

Vue Jsx Slot Props

Output of rendered html: