How to Use Component Slots in Vue.js

Today, I’m going to share how to use component slots in Vue.js. Let’s get started:

Table of Contents

  1. Slots
  2. Fallback Content
  3. Named Slots

Slots

Slots allow to pass data between two components. Let’s create a file called Component1.vue under the components folder & paste this code:

Component1.vue
<template>
 <div>
   <slot></slot>
 </div>
</template>

<script>
export default{
}
</script>

Let’s create another file named Component2.vue and paste this code:

Component2.vue
<template>
  <div>
    <Component1>
      <p>Lorem Ipsum is simply dummy...</p>
    </Component1>
  </div>
</template>

<script>
import Component1 from "./components/Component1.vue";
export default {
  components: {
    Component1
  }
};
</script>

If we pass any content between the <Component1> & </Component1> tags that will be rendered in the place of <slot></slot>.

Fallback Content

If the parent component doesn’t pass any data, the child will render any elements inside its <slot></slot> tag. Let’s see the example:

Component1.vue
<template>
 <div>
   <slot>
      <p>Default content.</p>
   </slot>
 </div>
</template>

<script>
export default{
}
</script>

Let’s remove the content from the parent component:

Component2.vue
<template>
  <div>
    <Component1></Component1>
  </div>
</template>

<script>
import Component1 from "./components/Component1.vue";
export default {
  components: {
    Component1
  }
};
</script>

Now parent will show the child’s content. This is called fallback.

Named Slots

Named slots help us to inject data in multiple places. This is the structure of named slots:

<slot name="your-name-id"></slot>

Let’s see an example. The component1.vue:

Component1.vue
<template>
 <div>
   <slot name="name1"></slot>
   <slot name="name2"></slot>
 </div>
</template>

<script>
export default{

}
</script>

The component2.vue:

Component2.vue
<template>
  <div>
    <Component1>
      <template v-slot:name1>
         <p>Name 1 content</p>
      </template>

      <template v-slot:name2>
         <p>Name 2 content</p>
      </template>
    </Component1>
  </div>
</template>

<script>
import Component1 from "./components/Component1.vue";
export default {
  components: {
    Component1
  }
};
</script>

That’s all.


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.