Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Can a Vue Template Have Multiple Root Nodes (Fragments)?

DZone's Guide to

Can a Vue Template Have Multiple Root Nodes (Fragments)?

It might sound a little weird at first, but if there's anyone who knows how to do it, it's this Vue developers. Read on for some expert JavaScripting!

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

If you try to create a Vue template without a root node, such as this:

<template>
  <div>Node 1</div>
  <div>Node 2</div>
</template>

You'll get a compilation and/or runtime error, as templates must have a single root element. Typically, you'll fix this problem by adding a "wrapper" div as a parent. This wrapper element has no display purpose, it's just there so your template complies with the single-root requirement.

<template>
  <div><!--I'm just here for wrapping purposes-->
    <div>Node 1</div>
    <div>Node 2</div>
  </div>
</template>

Having a wrapper like this is usually not a big deal, but there are scenarios where having a multi-root template is necessary. In this article, we'll look at why this is and provide some possible workarounds to the limitation.

Note: this article was originally posted here on the Vue.js Developers blog on 2018/09/11

Rendering Arrays

The are some situations where you may need your component to render an array of child nodes for inclusion in a parent component.

For example, some CSS features require a very particular hierarchy of elements to work correctly, like CSS grid or flex. Having a wrapper between the parent and children elements is not an option.

<template>
  <!--Flex won't work if there's a wrapper around the children-->
  <div style="display:flex">
    <FlexChildren/>
  </div>
</template>

There's also the issue where adding a wrapper element to a component may result in invalid HTML being rendered. For example, if you're building a table, a table row, <tr>, must only have table cells, <td>, for children.

<template>
  <table>
    <tr>
      <!--Having a div wrapper would make this invalid HTML-->
      <TableCells/>
    </tr>
  </table>
</template>

In short, the single-root requirement means the design pattern of a components that return child elements will not be possible in Vue.

Fragments

This single-root limitation was also an issue for React, but it provided an answer in version 16 with a feature called fragments. To use it, wrap your multi-root templates in the special React.Fragment element:

class Columns extends React.Component {
  render() {
    return (
      <React.Fragment>
        <td>Hello</td>
        <td>World</td>
      </React.Fragment>
    );
  }
}

This will render the children without the wrapper. There's even a neat short syntax <>:

class Columns extends React.Component {
  render() {
    return (
      <>
        <td>Hello</td>
        <td>World</td>
      </>
    );
  }
}

Fragments in Vue

Will there be a Vue equivalent of fragments? Probably not any time soon. The reason for this is that the virtual DOM diffing algorithm relies on components having a single root. According to Vue contributor Linus Borg:

"Allowing fragments requires significant changes to [the diffing] algorithm...it's not only important to make it work correctly but also to make it highly performant... That's a pretty hefty task... React waited for a complete re-write of its rendering layer to remove that restriction."

Functional Components With Render Fnctions

Functional components do not have the single-root limitation, however, as they don't need to be diffed in the virtual DOM the way stateful components do. This means if your component only needs to return static HTML (unlikely, to be honest), you're fine to have multiple root nodes.

There is still a caveat: you need to use a render function as vue-loader does not currently support the multi-root feature (although there is discussion about it).

TableRows.js

export default {
  functional: true,
  render: h => [
    h('tr', [
      h('td', 'foo'),
      h('td', 'bar'),
    ]),
    h('tr', [
      h('td', 'lorem'),
      h('td', 'ipsum'),
    ])
  ];
});

main.js

import TableRows from "TableRows";

new Vue({
  el: '#app',
  template: `<div id="app">
                <table>
                  <table-rows></table-rows>
                </table>
              </div>`,
  components: {
    TableRows
  }
});

Hack With Directives

There is a neat hack you can use to get around the single-root limitation. It involves using a custom directive, giving you access to the DOM. You manually move all the child elements from the wrapper into its parent, then delete the wrapper.

Before:

<parent>
  <wrapper>
    <child/>
    <child/>
  </wrapper>
</parent>

Intermediate step:

<parent>
  <wrapper/>
  <child/>
  <child/>
</parent>

After:

<parent>
  <!--<wrapper/> deleted-->
  <child/>
  <child/>
</parent>

It's a little tricky to get this to work, which is why it's great that a plugin called vue-fragments, by Julien Barbay, has been created.

vue-fragments

vue-fragments can be installed as a plugin in your Vue project:

import { Plugin } from "vue-fragments";
Vue.use(Plugin);

This plugin registers a global VFragment component which you use as a wrapper in your component templates, similar to the syntax of React fragments:

<template>
  <v-fragment>
    <div>Fragment 1</div>
    <div>Fragment 2</div>
  </v-fragment>
</template>

I'm not sure how robust this plugin is for all use cases — it seems like it might be a fragile — but for the experiments I did, it worked like a charm!

Get the latest Vue.js articles, tutorials and cool projects in your inbox with the Vue.js Developers Newsletter.

Take a look at an Indigo.Design sample application to learn more about how apps are created with design to code software.

Topics:
vue ,web components ,web dev ,vue.js tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}