Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 296
Michał Avatar asked Jan 27 '18 16:01

Michał


People also ask

What is inline template in Vue?

x Syntax x, Vue provided the inline-template attribute on child components to use its inner content as its template instead of treating it as distributed content. html <my-component inline-template> <div> <p>These are compiled as the component's own template.</

How do I use props in Vue template?

To specify the type of prop you want to use in Vue, you will use an object instead of an array. You'll use the name of the property as the key of each property, and the type as the value. If the type of the data passed does not match the prop type, Vue sends an alert (in development mode) in the console with a warning.

What is interpolation in VUE JS?

The most basic form of Vue interpolation is text interpolation. It's simply the process of displaying a string that's defined within your component logic.


1 Answers

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.

like image 153
kai Avatar answered Sep 23 '22 00:09

kai