[Vuejs]-How to conditional render vue.js on template tag?

2πŸ‘

βœ…

@xyiii pointed the error that is displayed in the console.

As you commented on @xyiii answer:

hmm so, Vue.js Doc example is wrong code?

Nope.
They are just explaining the case where you want to toggle multiple elements depending on same property.

So instead of doing it like this:

Title
Paragraph 1

Paragraph 2

You can group them in a template tag and do it like this:

<template v-if="ok">
<h1>Title</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</template>

<template> tag is just like a placeholder. It will not be rendered on to the DOM.

So you can have two root elements by mistake as:

<template v-if="ok">
    <div>Root element 1</div>
    <div>Root element 2</div>
</template>

So to prevent this vue throws an error.

To know why only one root element checkout @LinusBorg’s comment here.

πŸ‘€Vamsi Krishna

1πŸ‘

By the debugging console:

Cannot use <template> as component root element because it may contain
multiple nodes.

You basically need a root element and since a template tag can contain multiple elements, you are not allowed to use that as root element in vue.

Instead, use a div and your re-written example works:

<div id="app-3">
  <div v-if="ok">
    <h1>Title</h1>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
  </div>
</div>
πŸ‘€xyiii

Leave a comment