Vue3 Fundamentals · Rendering & Templates

Conditional rendering

Conditional rendering

A signed-in visitor and a signed-out visitor should see different words. You want the page to choose one branch or the other, the way an if chooses in JavaScript.

Vue has directives for exactly this. v-if renders its element only when the expression is true; v-else renders the alternative:

<p v-if="loggedIn">Welcome back!</p>
<p v-else>Please log in.</p>

Vue evaluates the condition and mounts the matching element. The other one is not in the DOM at all — it is created when the condition flips and removed when it flips back.

A chain may have several branches: v-if, then v-else-if with another condition, then a final v-else. The elements must sit next to each other, with nothing between them, so Vue knows they belong to one chain. Only one branch is ever rendered at a time.

Your job is to render one of two messages with v-if and v-else.

Challenge

The page always tells the visitor to log in, even when they are signed in. Export an App component from App.vue that renders Welcome back! when loggedIn is true and Please log in. otherwise, using v-if and v-else.

The Test mounts your component and reads the paragraph's text. The starter always prints the signed-out message, so the Test fails — branch on loggedIn.

App.vue
<script setup>
const loggedIn = true;
</script>

<template>
  <p>Please log in.</p>
</template>

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.