In Vue.js, if you want to conditionally render multiple elements via a v-if/v-else-if
directive you can wrap them inside <template>
tags and apply the directive to the <template>
tag, as explained here. However, you can also do the same with <div>
tags wrapping the multiple elements. Are there any noticeable performance benefits to using <template>
over <div>
or any other similar native HTML5 tag?
VueJS: vs or related for grouping elements for conditional rendering
Asked
Active
Viewed 1.7k times
29
tony19
- 125,647
- 18
- 229
- 307
Colin Michael Flaherty
- 786
- 2
- 7
- 15
2 Answers
62
I doubt there is a performance change but a big difference is that the <template>
node does not appear in the DOM.
This is an important distinction especially when grouping children that are the only valid node types for their parent such as list items, table rows, etc:
This is valid:
<ul>
<template v-if="something">
<li>Text</li>
<li>Text</li>
</template>
</ul>
This is not:
<ul>
<div v-if="something">
<li>Text</li>
<li>Text</li>
</div>
</ul>
Marty
- 39,033
- 19
- 93
- 162
-
2
Ah, I see. The example of conditionally rendering lists is a great one!
– Colin Michael Flaherty
Aug 24 '18 at 00:21
8
I know that the question is quite old, but I found out one more thing
if you use divs - your div will be in DOM, but empty, if v-if is false and it can make some spaces looks like margins
if you use template - you don't have anything in DOM and it just don't appear
Maria Gileto
- 81
- 1
- 3
Asked
Active
Viewed 1.7k times
29

tony19
- 125,647
- 18
- 229
- 307

Colin Michael Flaherty
- 786
- 2
- 7
- 15
2 Answers
62
I doubt there is a performance change but a big difference is that the <template>
node does not appear in the DOM.
This is an important distinction especially when grouping children that are the only valid node types for their parent such as list items, table rows, etc:
This is valid:
<ul>
<template v-if="something">
<li>Text</li>
<li>Text</li>
</template>
</ul>
This is not:
<ul>
<div v-if="something">
<li>Text</li>
<li>Text</li>
</div>
</ul>

Marty
- 39,033
- 19
- 93
- 162
-
2Ah, I see. The example of conditionally rendering lists is a great one! – Colin Michael Flaherty Aug 24 '18 at 00:21
8
I know that the question is quite old, but I found out one more thing
if you use divs - your div will be in DOM, but empty, if v-if is false and it can make some spaces looks like margins
if you use template - you don't have anything in DOM and it just don't appear

Maria Gileto
- 81
- 1
- 3