Allow more than 1 root element for Template

Allow more than 1 root element for Template

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

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:

Note: this article was originally posted here on the Vue.js Developers blog on 2018/09/11### Functional components with render functions

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!

Learn by Doing: Vue JS 2.0 the Right Way

Vue.js 2 Essentials: Build Your First Vue App

Getting started with Vuejs for development

Horizontal Feed Component with Sass and VueJs 2

Learn Vue 1 JS introduction to simple reactive JavaScript

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

10 Best Vue Icon Component For Your Vue.js App

In this article, I will collect 10 Vue icon component to bring more interactivity, better UI design to your Vue application.

Collection of 10 Vue Markdown Component for Vue.js App in 2020

Markdown is a way to style text on the web. The 10 Vue markdown components below will give you a clear view.

Collection of 15 Vue Input Component for Your Vue.js App

Vue input component gives you a baseline to create your own custom inputs. It consists of a prepend/append slot, messages, and a default slot. In this article I will share 15 Vue input components to you.