Home » vue » How to conditional render vue.js on template tag?

How to conditional render vue.js on template tag?

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m studying vue.js through reference document on Vue.js Reference Doc.

and then, i’m following up example. but, conditional part example dosen’t work.

this is my code.

<template id="app-3">
<div v-if="ok">
    <h1>Title</h1>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
</div>
</template>
<script src="vue.js"></script>
<script>
    var app = new Vue({
        el : '#app-3',
        data : {
            ok : true
        }
    });
</script>

and this code is work.

    <transition id="app-3">
    <template v-if="ok">
        <div>
            <h1>Title</h1>
            <p>Paragraph 1</p>
            <p>Paragraph 2</p>
        </div>
    </template>
</transition>
<script src="vue.js"></script>
<script>
    var app = new Vue({
        el : '#app-3',
        data : {
            ok : true
        }
    });
</script>

i want to know first code why doesn’t work!

Answers:

@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.

###

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>