Skip to content

What Is a Fragment in Vue?

In Vue, a fragment means a component template with more than one root element. The feature arrived with Vue 3. In Vue 2 every template had to have exactly one root element, so returning several elements meant wrapping them all in an unnecessary <div>.

In Vue 3 you can put several elements at the root of a template, and Vue renders them without an extra wrapper. This keeps table rows, list items and flex or grid layouts from being broken by needless wrappers.

A simple example:

Vue
<template>
  <!-- Vue 3: three root elements, no wrapper div -->
  <h1>Heading</h1>
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
</template>

This component returns the <h1> and the two <p> elements directly.

Watch out: attribute fallthrough

Attributes such as class or id given to a single-root component are added to its root element automatically. With several roots Vue cannot know which element should receive them and shows a warning. In that case pass them to the element you want explicitly with v-bind="$attrs":

VueCode fragment
<template>
  <header>Header</header>
  <main v-bind="$attrs">Content</main>
  <footer>Footer</footer>
</template>

Have a question about this article? Write to me