简体   繁体   中英

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

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.

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 :

Any use of <template> inside the main <template> of .vue files means that we want to use an invisible wrapper . The question now is when do we need to use invisible wrappers? The answer is simple: Whenever we want to use v-if , v-else or v-for directives for a group of elements (not a single element).

Therefore, in this case, we wrap all the mentioned group of elements using this:

<template v-if = " "></template>

and by doing this, we simply render the content between the above <template> tag, no need to create a redundant <div> , and then after rendering, the <template> tag itself will not exist in the DOM and so it does its job well as an invisible wrapper .

模板标签中的内容将被渲染到.vue文件中的视图中。

If you use a simple <div> , external CSS, images and other resources will be loaded even if your <div> is hidden using CSS.

Follow the below link for an explanation of why <template> was introduced in HTML5.

template introduction

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM