Reputation: 333
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!
Upvotes: 0
Views: 516
Reputation: 31352
@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 2You 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.
Upvotes: 2
Reputation: 112
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>
Upvotes: 1