Menu
CoddyTech

Conditional Branches

Part of the Fundamentals section of Coddy's Vue journey. Lesson 21 of 55.

Use v-if for an element that should exist only when a condition is true. This view shows Locked initially. Changing unlocked to true replaces it with Enter.

const unlocked = ref(false);
// <p v-if="unlocked">Enter</p>
// <p v-else>Locked</p>

Keep v-else immediately after its matching branch. For more than two cases, put v-else-if="condition" between them. Vue chooses the first true branch and removes inactive branches, so any local DOM state in removed elements is lost.

challenge icon

Challenge

Easy

Start with a closed desk. Button #toggle flips a boolean. When open, render p#result with Desk open; otherwise render p#closed with Desk closed. The inactive paragraph must be absent from the DOM.

Try it yourself

<!doctype html><html><head><meta charset="UTF-8"><title>Vue practice</title></head><body><div id="app"></div><script type="module" src="./main.js"></script></body></html>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals