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?
vue.js - VueJS: vs or related for grouping elements for conditional rendering
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
问问题
6512 次
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>
4
2 回答
40
我怀疑是否存在性能变化,但一个很大的区别是<template>
节点没有出现在 DOM 中。
这是一个重要的区别,尤其是在对作为其父节点的唯一有效节点类型的子节点进行分组时,例如列表项、表格行等:
这是有效的:
<ul>
<template v-if="something">
<li>Text</li>
<li>Text</li>
</template>
</ul>
这不是:
<ul>
<div v-if="something">
<li>Text</li>
<li>Text</li>
</div>
</ul>
于 2018-08-24T00:17:54.887 回答
0
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
于 2022-02-21T08:13:30.927 回答
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
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>
2 回答
我怀疑是否存在性能变化,但一个很大的区别是<template>
节点没有出现在 DOM 中。
这是一个重要的区别,尤其是在对作为其父节点的唯一有效节点类型的子节点进行分组时,例如列表项、表格行等:
这是有效的:
<ul>
<template v-if="something">
<li>Text</li>
<li>Text</li>
</template>
</ul>
这不是:
<ul>
<div v-if="something">
<li>Text</li>
<li>Text</li>
</div>
</ul>
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