Using Slot Injection in Vue.js with Templates

Posted by


In Vue.js, slots are a powerful feature that allows you to inject additional content into a component from the parent component. This can be useful for creating reusable components that can be customized in different ways depending on the context in which they are used. In this tutorial, we will take a look at how to use slots to inject templates into a Vue.js component.

Let’s start by creating a simple Vue component that uses a slot to inject content:

// MyComponent.vue
<template>
  <div>
    <!-- This is the default slot content -->
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: 'MyComponent'
}
</script>

In the code above, we have created a basic Vue component called MyComponent that contains a <slot> element in its template. This slot will be used to inject additional content into the component from the parent component.

Now, let’s create a parent component that uses the MyComponent component and injects some content into it:

// App.vue
<template>
  <div>
    <MyComponent>
      <!-- This is the content that will be injected into the slot -->
      <p>Hello, I am injected content!</p>
    </MyComponent>
  </div>
</template>

<script>
import MyComponent from './MyComponent.vue';

export default {
  name: 'App',
  components: {
    MyComponent
  }
}
</script>

<style>
</style>

In the code above, we have created a parent component called App that imports the MyComponent component and uses it in its template. Inside the <MyComponent> tags, we have added some content that will be injected into the slot of the MyComponent component.

When you run this code, you will see that the injected content is rendered inside the MyComponent component. This demonstrates how slots can be used to inject templates into Vue.js components and customize their behavior.

In addition to using slots to inject content into components, you can also use named slots to inject specific content into named slots within a component. This can be useful for creating more complex components that require different types of content to be injected into different parts of the component.

Overall, slots are a powerful feature in Vue.js that allow you to create flexible and customizable components. By understanding how slots work and how to use them effectively, you can create more dynamic and reusable components in your Vue.js applications.