Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade Teachers Spaces Get Certified Upgrade Teachers Spaces
   ❮   
     ❯   

Vue Tutorial

Vue HOMEVue IntroVue DirectivesVue v-bindVue v-ifVue v-showVue v-forVue EventsVue v-onVue MethodsVue Event ModifiersVue FormsVue v-modelVue CSS BindingVue Computed PropertiesVue WatchersVue Templates

Scaling Up

Vue Why, How and SetupVue First SFC PageVue ComponentsVue PropsVue v-for ComponentsVue $emit()Vue Fallthrough AttributesVue Scoped StylingVue Local ComponentsVue SlotsVue v-slotVue Scoped SlotsVue Dynamic ComponentsVue TeleportVue HTTP RequestVue Template RefsVue Lifecycle HooksVue Provide/InjectVue RoutingVue Form InputsVue AnimationsVue Animations with v-forVue BuildVue Composition API

Vue Reference

Vue Built-in AttributesVue Built-in ComponentsVue Built-in ElementsVue Component InstanceVue DirectivesVue Instance OptionsVue Lifecycle Hooks

Vue Examples

Vue ExamplesVue ExercisesVue QuizVue SyllabusVue Study PlanVue ServerVue Certificate

Vue v-if Directive


Example

Using thev-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

Thev-if directive is used to render an element conditionally.

Whenv-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 usingv-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 usev-if andv-for on the same tag. If both directives are used on the same tag,v-if will not have access to the variables used byv-for, becausev-if has higher priority thanv-for.


Directives for Conditional Rendering

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

DirectiveDetails
v-ifCan be used alone, or withv-else-if and/orv-else. If the condition insidev-if is 'true',v-else-if orv-else are not considered.
v-else-ifMust be used afterv-if or anotherv-else-if. If the condition insidev-else-if is 'true',v-else-if orv-else that comes after are not considered.
v-elseThis part will happen if the first part of the if-statement is false. Must be placed at the very end of the if-statement, afterv-if andv-else-if.

More Examples

Example 1

Usingv-if with a data property as the conditional expression, together withv-else.

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

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

Example 2

Usingv-if with a comparison check as the conditional expression, together withv-else.

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

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

Example 3

Usingv-if together withv-else-if andv-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

Usingv-if with a native JavaScript method as the conditional expression, together withv-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

Usingv-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

Usingv-if to create a component so that themounted 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

Usingv-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:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

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 ourterms of use,cookies andprivacy policy.

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


[8]ページ先頭

©2009-2025 Movatter.jp