Mikko
Mikko

Reputation: 1947

How do I use conditional rendering on template tag?

According to the Vue documentation I should be able to add the v-if condition to the <template> tag:

<template v-if="false">
  <div>Invisible text</div>
</template>

But this will not hide the element, however it does work when added to the child element:

<template>
  <div v-if="false">Invisible text</div>
</template>

Any suggestions?

I'm including the template in another .vue file:

<template>
  <div id="app">
    <H1 class= "main-title">Title</H1>
    <span class="components">
      <testtemplate></testtemplate>
    </span>
  </div>
</template>

Upvotes: 6

Views: 12402

Answers (2)

thanksd
thanksd

Reputation: 55674

The template tag of a single-file component is not rendered by Vue like normal <template> tags. It is simply one of the placeholders, along with <script> and <style> that vue-loader uses to build the component. The root element of that template is what will be the root in the component.

But, even if it worked the way you want, there would be no difference between your first and second example. Using v-if on the root will prevent the entire component's template from rendering if set to false.

Upvotes: 8

zapala.grzegorz
zapala.grzegorz

Reputation: 103

Had this problem with VUE3. Using SFC just nest tag template inside another tag template :

<template>
    <template v-if="false">
     You won't see this
    </template>
</template>

Upvotes: 8

Related Questions