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
EasyStart 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>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
2Reactive State
Reactive RefsUpdating Refs in ScriptEvent Handler ArgumentsReactive ObjectsRecap: Reactive State5Conditions and Lists
Conditional BranchesShow without UnmountingRendering ListsStable List IdentityRecap: Conditions8Component Communication
Emitting EventsEvent PayloadsLifting Shared StateDefault and Named SlotsRecap: Shared Panel11Project: Community Board
Board StructureAdding Community Tasks