Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Vue Tutorial

Vue HOME Vue Intro Vue Directives Vue v-bind Vue v-if Vue v-show Vue v-for Vue Events Vue v-on Vue Methods Vue Event Modifiers Vue Forms Vue v-model Vue CSS Binding Vue Computed Properties Vue Watchers Vue Templates

Scaling Up

Vue Why, How and Setup Vue First SFC Page Vue Components Vue Props Vue v-for Components Vue $emit() Vue Fallthrough Attributes Vue Scoped Styling Vue Local Components Vue Slots Vue v-slot Vue Scoped Slots Vue Dynamic Components Vue Teleport Vue HTTP Request Vue Template Refs Vue Lifecycle Hooks Vue Provide/Inject Vue Routing Vue Form Inputs Vue Animations Vue Animations with v-for Vue Build Vue Composition API

Vue Reference

Vue Built-in Attributes Vue Built-in Components Vue Built-in Elements Vue Component Instance Vue Directives Vue Instance Options Vue Lifecycle Hooks

Vue Examples

Vue Examples Vue Exercises Vue Quiz Vue Server Vue Certificate

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


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.