← Back to Vue.js Course | Chapter 2: Template Syntax | Lesson 3 of 7

v-if/v-else

v-if adds an element to the page only when its condition is true, with v-else-if and v-else for alternatives.

In this page:

  1. v-if/v-else
Syntax
markup
<p v-if="condition">shown when true</p>
<p v-else-if="other_condition">other</p>
<p v-else>otherwise</p>

v-if/v-else

v-if renders or removes the element from the DOM based on a condition. v-else-if and v-else must directly follow. To toggle several elements at once, put v-if on a template tag.

Removing and creating elements has a cost, so use v-show for frequent toggling.

Note: v-else must come immediately after a v-if or v-else-if element.

Example: v-if/v-else

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
  <p v-if="score >= 90">Grade A</p>
  <p v-else-if="score >= 75">Grade B</p>
  <p v-else>Keep practising</p>
  <template v-if="loggedIn">
    <h3>Welcome back</h3>
    <p>You have new mail.</p>
  </template>
</div>
<script>
  Vue.createApp({
    data() { return { score: 82, loggedIn: true }; },
  }).mount("#app");
</script>
</body>
</html>

<!-- Output:
Rendered: Grade BWelcome backYou have new mail.
-->
Live Example
Related Topics
Common Mistakes
  1. Placing other elements between v-if and v-else
  2. Using v-if and v-for together on one element
  3. Using v-if for rapid toggles
Chapter Summary
  • v-if adds or removes elements
  • v-else-if and v-else follow it
  • template v-if groups elements
  • Prefer v-show for frequent toggles
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.