Does a Vuejs component template need only root one element?
Asked Answered
S

4

6

I did not saw anything about this in docs, maybe I did not search enough, but components template seems to work "better" with a root element (better means: it works without root element with Laravel elixir running gulp but running gulp --production displays only the first element).

Do I need to have only one root element inside <template>?

In other words, is this template code allowed in Vue 2?

<template>
  <div>A</div>
  <div>B</div>
</template>
Slump answered 4/11, 2016 at 9:23 Comment(0)
Q
9

Every component must have exactly one root element. Fragment instances are no longer allowed. If you have a template like this:

<p>foo</p>
<p>bar</p>

It’s recommended to simply wrap the entire contents in a new element, like this:

<div>
  <p>foo</p>
  <p>bar</p>
</div>

VueJS Docs

Query answered 4/11, 2016 at 9:31 Comment(0)
S
5

It may compile, but Vue will throw you out the following warning:

[Vue warn]: Component template should contain exactly one root element:

And only show the first element in the template, so you have to make sure you wrap your template in one root level tag like so:

<template>
  <div>
    <div>A</div>
    <div>B</div>
  </div>
</template>

If you look in the developer tools console on the following JSFiddle you should see what I mean:

https://jsfiddle.net/woLwz98n/

I'll also take the chance to thank you for your laravel-log-viewer, I use it all the time and it's excellent!

Scarron answered 4/11, 2016 at 9:31 Comment(0)
U
3

Yes it is required for Vue 2.0 templates to have single root element. Just create an parent div and place all your component div inside it.

<template>
  <div>
    <div>A</div>
    <div>B</div>
  </div>
</template>

Vue.js creator mentions the same in this post:
https://github.com/vuejs/vue-loader/issues/384

Unknow answered 4/11, 2016 at 9:36 Comment(0)
K
3

Further to the provided answers, I thought I'd just add my two cents as it may assist someone else. I had a child component (of table rows) and I kept putting wrapping divs around the table rows attempting the solutions posed above - but then I realised the parent component was the part that needed the wrapping, not the child & the issue was solved. So if you are in a parent / child component situation encountering this error - wrap a div around your parent template code.

Keslie answered 6/4, 2017 at 12:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.