Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS: <template> vs <div> or related for grouping elements for conditional rendering

Tags:

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?

like image 827
Colin Michael Flaherty Avatar asked Aug 24 '18 00:08

Colin Michael Flaherty


People also ask

What does template tag do in Vue?

Vue uses an HTML-based template syntax that allows you to declaratively bind the rendered DOM to the underlying component instance's data.

What is the difference between V-show and V-if directives?

v-if - Only renders the element to the DOM if the expression passes. v-show - Renders all elements to the DOM and then uses the CSS display property to hide elements if the expression fails.

Which Vue attribute is used to display an HTML element based on a condition?

v-else-if directive is a Vue. js directive used to toggle the display CSS property of an element depending on a condition when the if condition is not satisfied.

Can we use V-if and V-show together?

If v-if == true and v-show changes from true to false , the leave transition occurs as expected. If v-show== true and v-if changes from true to false , the element is immediately removed, no transition occurs. My use case for this is using both v-if and v-show around media ( img , video ).


1 Answers

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>
like image 89
Marty Avatar answered Sep 23 '22 14:09

Marty