0
0
Vueframework~30 mins

Why conditional rendering matters in Vue - See It in Action

Choose your learning style9 modes available
Why conditional rendering matters
📖 Scenario: You are building a simple Vue app that shows a welcome message only when the user is logged in. This is common in real websites where some parts appear only if you are signed in.
🎯 Goal: Create a Vue component that conditionally shows a welcome message based on a logged-in status. You will learn how to use Vue's conditional rendering to control what the user sees.
📋 What You'll Learn
Create a reactive variable called isLoggedIn with initial value false.
Create a button that toggles isLoggedIn between true and false.
Use Vue's v-if directive to show a <p> with text Welcome back, user! only when isLoggedIn is true.
Use Vue 3 Composition API with <script setup> and ref.
💡 Why This Matters
🌍 Real World
Many websites show or hide parts of the page depending on whether a user is logged in. Conditional rendering helps create dynamic, user-friendly interfaces.
💼 Career
Understanding conditional rendering is essential for frontend developers to build interactive apps that respond to user actions and state changes.
Progress0 / 4 steps
1
Set up the reactive login state
Inside the <script setup> block, create a reactive variable called isLoggedIn using ref and set it to false.
Vue
Need a hint?

Use import { ref } from 'vue' and then const isLoggedIn = ref(false).

2
Add a button to toggle login state
In the <template>, add a <button> that toggles isLoggedIn between true and false when clicked. Use the @click event with an inline arrow function.
Vue
Need a hint?

Use <button @click="() => isLoggedIn.value = !isLoggedIn.value"> to toggle the value.

3
Use v-if to conditionally show welcome message
Below the button in the <template>, add a <p> element with text Welcome back, user! that only appears when isLoggedIn is true. Use Vue's v-if directive with isLoggedIn.
Vue
Need a hint?

Use <p v-if="isLoggedIn.value">Welcome back, user!</p> to show the message only when logged in.

4
Add accessibility and finalize component
Add an aria-pressed attribute to the button that reflects the isLoggedIn state for accessibility. The attribute value should be isLoggedIn. This helps screen readers understand the toggle state.
Vue
Need a hint?

Bind aria-pressed to isLoggedIn using :aria-pressed="isLoggedIn.value".