Reputation: 908
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>
?
Upvotes: 20
Views: 24158
Reputation: 25312
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 :
Upvotes: 10
Reputation: 269
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.
Upvotes: 8
Reputation: 1405
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.
Upvotes: 0
Reputation: 231
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.
Upvotes: 23
Reputation: 500
Content within Template tags will be rendered into into a view in a .vue
file.
Upvotes: 0