🎓 A1Learner
🔍
0 of 50 lessons completed

Conditional Rendering in Vue

Conditional rendering means showing different markup for different values. Vue picks one branch from a v-if chain and draws only that branch.

One branch

role is admin, so the first branch draws.

<p v-if="role === 'admin'">Admin tools</p>

The whole chain

The three branches cover admin, editor, and everyone else.

<p v-if="role === 'admin'">Admin tools</p>
<p v-else-if="role === 'editor'">Editor tools</p>
<p v-else>Reader view</p>

The fallback branch

v-else draws when no condition above it is true.

<p v-else>Reader view</p>

Example

<script setup>
import { ref } from 'vue'
const role = ref('admin')
</script>
<template>
  <div>
    <p v-if="role === 'admin'">Admin tools</p>
    <p v-else-if="role === 'editor'">Editor tools</p>
    <p v-else>Reader view</p>
  </div>
</template>

Key points

  • v-if draws its element only when its condition is true.
  • v-else-if checks the next condition when v-if is false.
  • v-else draws its element when every condition above it is false.
  • Only one branch of the chain appears on the page.
  • The chain reads from top to bottom, and Vue stops at the first true condition.

In this example, role is a ref with the value admin. The template holds a chain of three paragraphs. v-if checks for admin first. v-else-if checks for editor next. v-else covers every other value. The first render shows Admin tools. A verified variant with role set to editor shows Editor tools. A variant with role set to reader shows Reader view.

Note

A chain needs v-if first, then v-else-if, then v-else last.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does v-else draw?