Blog>
Snippets

Combining Fragments with Slots

Use fragments in combination with named slots to insert content into a component template without additional wrappers.
// ParentComponent.vue
<template>
  <ChildComponent>
    <template #header>
      <h1>Welcome</h1>
    </template>
    <template #footer>
      <p>Goodbye</p>
    </template>
  </ChildComponent>
</template>

<script>
// Import ChildComponent before using it
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  }
};
</script>
This code example is part of a Vue.js parent component (ParentComponent.vue). It uses named slots ('header' and 'footer') to pass fragments of template to a child component (ChildComponent.vue) without any unnecessary wrapper divs.
// ChildComponent.vue
<template>
  <div>
    <!-- Slot for header content -->
    <slot name="header"></slot>

    <!-- Main content of the child goes here -->
    <p>Main content of the child component.</p>

    <!-- Slot for footer content -->
    <slot name="footer"></slot>
  </div>
</template>

<script>
export default {
  // Component logic goes here
};
</script>
This code example provides the ChildComponent.vue which defines the named slots ('header' and 'footer') where the parent component can inject its template fragments.