What's the use of <template> within a <template> in VueJS 2?

Michał picture Michał · Jan 27, 2018 · Viewed 9.3k times · Source

I'm trying to understand the use case of <template> and it's functions. Having referenced the docs, I'm still left fairly confused.

Considering the following code in any.vue file:

<template>
   <div class="top-right links">

      <!-- Why use <template> here instead of a div, for example? -->
      <template v-if="authenticated">
         <router-link :to="{ name: 'home' }">
            {{ $t('home') }}
         </router-link>
      </template>

      <template v-else>
         <router-link :to="{ name: 'login' }">
            {{ $t('login') }}
         </router-link>
      </template>

   </div>
</template>

Why would we use <template> instead of just a simple <div>, and how is using <template> different than say, using a <custom-component>?

Answer

kai picture kai · Jan 28, 2018

From my understanding, using <template> will not render out extra elements in the DOM. It's especially useful when you are conditionally adding multiple elements that don't exactly need a parent <div>. If the <div> serves no purpose other than to conditional multiple tags, that can be done without having an extra <div>.

I typically will default to using <template> until I need a <div> or other elements as a parent container, mainly to apply styles.