DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Document Generation API: How to Automate Personalized Document Creation at Scale
  • Reproducibility as a Competitive Edge: Why Minimal Config Beats Complex Install Scripts
  • Building a Card Layout Using CSS Subgrid
  • How To Build AI-Powered Prompt Templates Using the Salesforce Prompt Builder

Trending

  • AI Coding Agent Guardrails: Finding Gaps in Tool Permissions
  • Treat Salesforce Configuration Like Code: Release Discipline in a Copado Pipeline
  • Decoupling a Data Pipeline From the Tables It Was Never Supposed to Depend On
  • Spring AI on Local LLMs

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

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!

By 
Anthony Gore
·
Updated Jan. 06, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
32.9K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

HTML




x


 
1
<template>
2
  <div>Node 1</div>
3
  <div>Node 2</div>
4
</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.

HTML




xxxxxxxxxx
1


 
1
<template>
2
  <div><!--I'm just here for wrapping purposes-->
3
    <div>Node 1</div>
4
    <div>Node 2</div>
5
  </div>
6
</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.

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.

HTML




xxxxxxxxxx
1


 
1
<template>
2
  <!--Flex won't work if there's a wrapper around the children-->
3
  <div style="display:flex">
4
    <FlexChildren/>
5
  </div>
6
</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.

HTML




xxxxxxxxxx
1


 
1
<template>
2
  <table>
3
    <tr>
4
      <!--Having a div wrapper would make this invalid HTML-->
5
      <TableCells/>
6
    </tr>
7
  </table>
8
</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:

JavaScript




xxxxxxxxxx
1
10


 
1
class Columns extends React.Component {
2
  render() {
3
    return (
4
      <React.Fragment>
5
        <td>Hello</td>
6
        <td>World</td>
7
      </React.Fragment>
8
    );
9
  }
10
}



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

JavaScript




xxxxxxxxxx
1
10


 
1
class Columns extends React.Component {
2
  render() {
3
    return (
4
      <>
5
        <td>Hello</td>
6
        <td>World</td>
7
      </>
8
    );
9
  }
10
}



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

JavaScript




xxxxxxxxxx
1
13


 
1
export default {
2
  functional: true,
3
  render: h => [
4
    h('tr', [
5
      h('td', 'foo'),
6
      h('td', 'bar'),
7
    ]),
8
    h('tr', [
9
      h('td', 'lorem'),
10
      h('td', 'ipsum'),
11
    ])
12
  ];
13
});



main.js

JavaScript




xxxxxxxxxx
1
13


 
1
import TableRows from "TableRows";
2

          
3
new Vue({
4
  el: '#app',
5
  template: `<div id="app">
6
                <table>
7
                  <table-rows></table-rows>
8
                </table>
9
              </div>`,
10
  components: {
11
    TableRows
12
  }
13
});



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:

HTML




xxxxxxxxxx
1


 
1
<parent>
2
  <wrapper>
3
    <child/>
4
    <child/>
5
  </wrapper>
6
</parent>



Intermediate step:

HTML




xxxxxxxxxx
1


 
1
<parent>
2
  <wrapper/>
3
  <child/>
4
  <child/>
5
</parent>



After:

HTML




xxxxxxxxxx
1


 
1
<parent>
2
  <!--<wrapper/> deleted-->
3
  <child/>
4
  <child/>
5
</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:

JavaScript




xxxxxxxxxx
1


 
1
import { Plugin } from "vue-fragments";
2
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:

HTML




xxxxxxxxxx
1


 
1
<template>
2
  <v-fragment>
3
    <div>Fragment 1</div>
4
    <div>Fragment 2</div>
5
  </v-fragment>
6
</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.

Template Fragment (logic)

Published at DZone with permission of Anthony Gore. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Document Generation API: How to Automate Personalized Document Creation at Scale
  • Reproducibility as a Competitive Edge: Why Minimal Config Beats Complex Install Scripts
  • Building a Card Layout Using CSS Subgrid
  • How To Build AI-Powered Prompt Templates Using the Salesforce Prompt Builder

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook