Vue v-else Directive


Example

Using the v-else directive to create a <div> element when all conditions above are 'false'.

<p v-if="word === 'apple'">The word is 'apple'.</p>
<p v-else-if="word === 'pizza'">The word is 'pizza'</p>
<div v-else>
  <img src="/img_question.svg" alt="question mark">
  <p>The word is not 'apple', and it is not 'pizza'</p>
</div>
Run Example »

See more examples below.


Definition and Usage

The v-else directive is used to render an element in case all conditions above in the if statement evaluates to 'false'.

The v-else directive can only be used after an element with v-if or v-else-if.

The v-else directive is used without an expression.

When v-else causes an element to toggle:

  • 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.

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-else to write "Not in stock" when the typewriter count is 0.

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

Using v-else to show a certain text when the sentence does not contain 'pizza' or 'burrito'.

<div id="app">
  <div v-if="text.includes('pizza')">
    <p>The text includes the word 'pizza'</p>
    <img src="img_pizza.svg">
  </div>
  <div v-else-if="text.includes('burrito')">
    <p>The text includes the word 'burrito', but not 'pizza'</p>
    <img src="img_burrito.svg">
  </div>
  <p v-else>The words 'pizza' or 'burrito' are not found in the text</p>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
  const app = Vue.createApp({
    data() {
      return {
        text: 'I like Thai beef salad, pho soup and tagine.'
      }
    }
  })
  app.mount('#app')
</script>
Try it Yourself »

Related Pages

Vue Tutorial: Vue v-if Directive

Vue Reference: Vue v-if Directive

Vue Reference: Vue v-else-if Directive

Vue Tutorial: Vue Animations

Vue Tutorial: Vue Lifecycle Hooks


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