javascriptvue.jsvuejs2templating

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


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>?


Solution

  • You are right, in your case you should simply use this :

    <template>
       <div class="top-right links">
         <router-link v-if="authenticated" :to="{ name: 'home' }">
            {{ $t('home') }}
         </router-link>
         <router-link v-else :to="{ name: 'login' }">
            {{ $t('login') }}
         </router-link>
       </div>
    </template>
    

    But let's say you need conditional multiple tags without using a parent tag :

    <template v-if="ok">
      <h1>Title</h1>
      <p>Paragraph 1</p>
    </template>
    

    Read more :