How to use slots in VueJS?

Hi Friends đź‘‹,

Welcome To SortoutCode! ❤️

To use slots in VueJS. We are going to use <slot> in the child components. Using the slots we can pass data but also we can pass the template fragments and pass that template fragment from the parent component to the child component and render within its template.

Short solution

ChildComp.vue

// template fragments are rendered in the child component using the
<slot></slot> //this is the slot outlet 

Today, I am going to show you How you use slots in VueJS?

Table of Content

  • Setup the Vue (Optional)
  • Create FirstComponent.vue and import it into App.js
  • How to use slots?

This article will guide you to How do I use slots in vueJS?

Setup the Vue.js

First, we have to install the Vue project, I had installed the vueJS in my system. If you haven’t installed or have any problem with installation you can follow this article, it will show you step by step process of installation.

How to Install the VueJS project?

Create FirstComponent.vue and import it into App.js

Create the new component in the src/components/ components folder. The component name is FirstComponent.vue and imported into the App.js file:

App.js

<template>
  <FirstComp />
</template>

<script>
import FirstComp from "./components/FirstComp.vue";
export default {
  name: "App",
  components: {
    FirstComp: FirstComp,
  },
};
</script>

How to use slots?

To use the slots in VueJS. we are going to use the <slot></slot> slot outlet.Using the props we can pass the data from parent components to child components. But using the slots we can pass the data but also template fragment means HTML tags from the parent component and child component show these parent template fragments within its template. Let’s see the example for a better understanding:

First, we are going to create the child component ChildComp.vue and create the slot outlet.

ChildComp.vue

<template>
  <div>
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: "ChildComp",
};
</script>

After that, we are going to create the parent component that is FirstComp.vue and import the ChildComp.vue, and add some content with some CSS.

FirstComp.vue

<template>
  <h1>Welcome to Sortoutcode.com</h1>
  <p>This is parent Component.</p>
  <ChiildComp>
    <div style="color: white; background-color: grey; height: 150px">
      <p style="padding-top: 25px">Hii, This is ChildComp.</p>
      <p>This is Child Components</p>
    </div>
  </ChiildComp>
</template>

<script>
import ChiildComp from "./ChildComp";
export default {
  name: "FirstComp",
};
</script>

For now, let’s check the output.

Output

Slots in VueJS

Links

Here, is the above program code sandbox link of how to use slots in vue js. Then you can use it whenever you went and do the changes as per your requirements.

Codesandbox

All the best đź‘Ť.

Follow me on Twitter