panthro
panthro

Reputation: 24061

v-if on a component template tag

From the docs:

Because v-if is a directive, it has to be attached to a single element. But what if we want to toggle more than one element? In this case we can use v-if on a element, which serves as an invisible wrapper. The final rendered result will not include the element.

But on my template in my component:

<template v-if="false">
    <div>
       ....
    </div>
</template>

But the component still renders.

I ask because I want a hook on the component so if v-if is true, I can do some code in beforeMounted and beforeDestroyed if false.

Upvotes: 1

Views: 6355

Answers (3)

Joel Walkley
Joel Walkley

Reputation: 21

Your reference to the docs is correct, you can use a v-if on a template tag. However, I believe conditionals on the top-level <template> in a Single File Component are ignored.

To achieve the effect showed in the docs (conditional render a template) that template needs to be within the top-level template section.

Example:

<script>
// your script section
</script>
<template>
  
  <template v-if="false">
    <div>
       ....
    </div>
  </template>

</template>
<style>
// your style section
</style>

Upvotes: 1

Arthur Kuznetsov
Arthur Kuznetsov

Reputation: 41

As Lucas Katayama said, you cannot use v-if inside SFC, but another way to hide you component is use v-if on this component in its parent component.

Upvotes: 0

Lucas Katayama
Lucas Katayama

Reputation: 4570

If I undestood what are you doing...

You're putting v-if int the template tag ina .vue file right? Like this

// component.vue
<template v-if="false">
   <div>
     My Component
   </div>
</template>
<script>
export default {
     name: 'my-component'
};
</script>
<styles>
</styles>

Right?

If YES, you are doing it wrong.

The template there is a tag for Webpack Vue Loader to load the component template.

So the if must go inside the template tag.

// component.vue
<template>
   <div v-if="false">
     My Component
   </div>
</template>
<script>
export default {
     name: 'my-component'
};
</script>
<styles>
</styles>

If you need to "hide" multiple elements, just encapsulate into another div.

Upvotes: 1

Related Questions