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.