DEV Community

Cover image for What is the v-if directive?
Leonardo Cunha
Leonardo Cunha

Posted on • Updated on

What is the v-if directive?

Definition

Looking through the documentation, v-if is a directive that can be used to:

"Conditionally render a block".

This means it allows you to display a particular data type only if it satisfies a specific requirement.

Also, this directive allows you to conditionally render one element and a set of elements inside the template tag.

You can also create an inside logic to render your elements with the support of the directives: v-else-if and v-else. You are using the classic programming logic principles.

Example

Let's see a quick example:

HTML:

<template>
  <div id="app">
    <h3>Do you live without coffee?</h3>
    <input v-model="answer" type="radio" id="yes" value="yes" />
    <label for="yes">Yes</label>
    <br />

    <input v-model="answer" type="radio" id="no" value="no" />
    <label for="no">No</label>
    <br />

    <p v-if="answer === 'yes'" class="answer">How? πŸ€”</p>
    <p v-else-if="answer === 'no'" class="answer">Oh, me too πŸ˜… β˜•</p>
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode

CSS:

#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

.answer {
  font-size: 30px;
}
Enter fullscreen mode Exit fullscreen mode

JavaScript:

export default {
  data() {
    return {
      answer: ""
    };
  }
};
Enter fullscreen mode Exit fullscreen mode

Notice initially, neither of the conditionals is satisfied. The answer property has its initial value equal to an empty string.

And, inside our app div, the p tags attached to our v-if and v-else-if aren't even shown in the DOM:

div_initially

However, with the v-model directive help, we updated the answer property, attach it to a new value based on the input the user chooses.

Once the answer property has a new value, the v-if checks if it satisfies our condition. In the first case, if the value equals the string "yes".

In case this is true(the answer has this value), the first p tag is mounted in the DOM:

yes_answer

On the other hand, if the second conditional has been achieved(the answer has the value equal to the string "no"), it displays the second p tag:

no_answer

See the power we got just using these two directives?

Restrictions

v-if, v-else-if, and v-else directives must be siblings in your template. Please don't put them apart from each other.

Be careful

As you notice, we mounted an entire element in our DOM. In this case, the cost is low. Although speaking in a significant context, some alternatives may suit you better as the use of the directive v-show. We'll be able to cover that later.

Top comments (0)