Vue v-if

Vue v-if Directive

Conditional rendering is one of the most powerful features in Vue.

The v-if directive is used to conditionally render a block of HTML code.

The HTML element will only be built and rendered if the directive's expression returns a "truthy" value.


How v-if Works

If the variable attached to v-if is true, the element appears on the page.

If the variable changes to false, Vue completely destroys and removes the element from the DOM.

This physical removal keeps the browser memory clean and fast!

v-if Example:

<div id="app">
  <h2 v-if="userIsLoggedIn">Welcome back, User!</h2>
</div>

<script> const app = Vue.createApp({ data() { return { userIsLoggedIn: true } } }); app.mount('#app'); </script>


The v-else Directive

You can use the v-else directive to indicate an "else block" for v-if.

A v-else element must immediately follow a v-if element in your HTML code, otherwise Vue won't recognize it.

v-else Example:

<div id="app">
  <h2 v-if="userIsLoggedIn">Dashboard</h2>
  <h2 v-else>Please log in to continue.</h2>
</div>

The v-else-if Directive

The v-else-if directive serves as an "else if block".

It can be chained multiple times to handle various different conditions.

Just like v-else, it must immediately follow a v-if or another v-else-if element.

v-else-if Example:

<div v-if="type === 'A'">Type A</div>
<div v-else-if="type === 'B'">Type B</div>
<div v-else-if="type === 'C'">Type C</div>
<div v-else>Not A, B, or C</div>

Exercise 1 of 2

?

What happens to a DOM element if its v-if condition evaluates to false?

Exercise 2 of 2

?

Can you place a <br> tag between a v-if element and a v-else element?