Vue v-if Directive


Example

Using the v-if directive to create a <div> element if the condition is 'true'.

<div v-if="createImgDiv">
  <img src="/img_apple.svg" alt="apple">
  <p>This is an apple.</p>
</div>
Run Example »

See more examples below.


Definition and Usage

The v-if directive is used to render an element conditionally.

When v-if is used on an element, it must be followed by an expression:

  • If the expression evaluates to 'true', the element and all its content is created in the DOM.
  • If the expression evaluates to 'false' the element is destroyed.

When an element is toggled using v-if:

  • We can use the built-in <Transition> component to animate when the element enters and leaves the DOM.
  • Lifecycle hooks such as 'mounted' and 'unmounted' are triggered.

Note: It is not recommended to use v-if and v-for on the same tag. If both directives are used on the same tag, v-if will not have access to the variables used by v-for, because v-if has higher priority than v-for.


Directives for Conditional Rendering

This overview describes how the different Vue directives used for conditional rendering are used together.

Directive Details
v-if Can be used alone, or with v-else-if and/or v-else. If the condition inside v-if is 'true', v-else-if or v-else are not considered.
v-else-if Must be used after v-if or another v-else-if. If the condition inside v-else-if is 'true', v-else-if or v-else that comes after are not considered.
v-else This part will happen if the first part of the if-statement is false. Must be placed at the very end of the if-statement, after v-if and v-else-if.

More Examples

Example 1

Using v-if with a data property as the conditional expression, together with v-else.

<p v-if="typewritersInStock">
  in stock
</p>

<p v-else>
  not in stock
</p>
Try it Yourself »

Example 2

Using v-if with a comparison check as the conditional expression, together with v-else.

<p v-if="typewriterCount > 0">
  in stock
</p>

<p v-else>
  not in stock
</p>
Try it Yourself »

Example 3

Using v-if together with v-else-if and v-else to display a status message based on the number of typewriters in storage.

<p v-if="typewriterCount>3">
  In stock
</p>

<p v-else-if="typewriterCount>0">
  Very few left!
</p>

<p v-else>
  Not in stock
</p>
Try it Yourself »

Example 4

Using v-if with a native JavaScript method as the conditional expression, together with v-else.

<div id="app">
  <p v-if="text.includes('pizza')">The text includes the word 'pizza'</p>
  <p v-else>The word 'pizza' is not found in the text</p>
</div>
data() {
  return {
    text: 'I like taco, pizza, Thai beef salad, pho soup and tagine.'
  }
}
Try it Yourself »

Example 5

Using v-if to render a <div> tag when data is received from the API.

<template>
  <h1>Example</h1>
  <p>Click the button to fetch data with an HTTP request.</p>
  <p>Each click generates an object with a random user from <a href="https://random-data-api.com/" target="_blank">https://random-data-api.com/</a>.</p>
  <p>The robot avatars are lovingly delivered by <a href="http://Robohash.org" target="_blank">RoboHash</a>.</p>
  <button @click="fetchData">Fetch data</button>
  <div v-if="data" id="dataDiv">
    <img :src="data.avatar" alt="avatar">
    <pre>{{ data.first_name + " " + data.last_name }}</pre>
    <p>"{{ data.employment.title }}"</p>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        data: null,
      };
    },
    methods: {
      async fetchData() {      
        const response = await fetch("https://random-data-api.com/api/v2/users"); 
        this.data = await response.json();
      },    
    }
  };
</script>

<style>
#dataDiv {
  width: 240px;
  background-color: aquamarine;
  border: solid black 1px;
  margin-top: 10px;
  padding: 10px;
}
#dataDiv > img {
  width: 100%;
}
pre {
  font-size: larger;
  font-weight: bold;
}
</style>
Run Example »

Example 6

Using v-if to create a component so that the mounted lifecycle hook is triggered.

CompOne.vue:

<template>
    <h2>Component</h2>
    <p>Right after this component is added to the DOM, the mounted() function is called and we can add code to that mounted() function. In this example, an alert popup box appears after this component is mounted.</p>
    <p><strong>Note:</strong> The reason that the alert is visible before the component is visible is because the alert is called before the browser gets to render the component to the screen.</p>
  </template>
  
  <script>
  export default {
    mounted() {
      alert("The component is mounted!");
    }
  }
  </script>

App.vue:

<template>
  <h1>The 'mounted' Lifecycle Hook</h1>
  <button @click="this.activeComp = !this.activeComp">Create component</button>
  <div>
    <comp-one v-if="activeComp"></comp-one>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeComp: false
    }
  }
}
</script>

<style scoped>
  div {
    border: dashed black 1px;
    border-radius: 10px;
    padding: 20px;
    margin: 10px;
    width: 400px;
    background-color: lightgreen;
  }
</style>
Run Example »

Example 7

Using v-if to toggle a <p> element so that animations are triggered.

<template>
  <h1>Add/Remove <p> Tag</h1>
  <button @click="this.exists = !this.exists">{{btnText}}</button><br>
  <Transition>
    <p v-if="exists">Hello World!</p>
  </Transition>
</template>

<script>
export default {
  data() {
    return {
      exists: false
    }
  },
  computed: {
    btnText() {
      if(this.exists) {
        return 'Remove';
      }
      else {
        return 'Add';
      }
    }
  }
}
</script>

<style scoped>
  .v-enter-from {
    opacity: 0;
    translate: -100px 0;
  }
  .v-enter-to {
    opacity: 1;
    translate: 0 0;
  }
  .v-leave-from {
    opacity: 1;
    translate: 0 0;
  }
  .v-leave-to {
    opacity: 0;
    translate: 100px 0;
  }
  p {
    background-color: lightgreen;
    display: inline-block;
    padding: 10px;
    transition: all 0.5s;
  }
</style>
Run Example »

Related Pages

Vue Tutorial: Vue v-if Directive

Vue Reference: Vue v-else-if Directive

Vue Reference: Vue v-else Directive

Vue Tutorial: Vue Animations

Vue Tutorial: Vue Lifecycle Hooks


Copyright 1999-2023 by Refsnes Data. All Rights Reserved.