0
0
Vueframework~5 mins

Why conditional rendering matters in Vue

Choose your learning style9 modes available
Introduction

Conditional rendering helps show or hide parts of a webpage based on what the user needs or what is happening. It makes the page smarter and easier to use.

Show a login form only when the user is not logged in.
Display a loading spinner while data is being fetched.
Hide a button after it is clicked to prevent multiple clicks.
Show different messages based on user choices.
Display error messages only when there is a problem.
Syntax
Vue
<template>
  <div>
    <p v-if="condition">This shows if condition is true.</p>
    <p v-else>This shows if condition is false.</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'
const condition = ref(true)
</script>
Use v-if to show elements only when a condition is true.
Use v-else to show elements when the v-if condition is false.
Examples
Shows a welcome message if the user is logged in, otherwise asks to log in.
Vue
<p v-if="isLoggedIn">Welcome back!</p>
<p v-else>Please log in.</p>
Displays a loading message while data loads, then shows the content.
Vue
<div v-if="loading">Loading...</div>
<div v-else>Content loaded.</div>
Shows a submit button until the form is submitted, then thanks the user.
Vue
<button v-if="!submitted" @click="submitForm">Submit</button>
<p v-else>Thank you for submitting!</p>
Sample Program

This Vue component shows a button that toggles a message on and off. When you click the button, the message changes between visible and hidden using conditional rendering.

Vue
<template>
  <section>
    <button @click="toggle">Toggle Message</button>
    <p v-if="showMessage">Hello! You can see this message.</p>
    <p v-else>The message is hidden.</p>
  </section>
</template>

<script setup>
import { ref } from 'vue'
const showMessage = ref(true)
function toggle() {
  showMessage.value = !showMessage.value
}
</script>
OutputSuccess
Important Notes

Conditional rendering keeps your app fast by only showing what is needed.

Use v-if for conditions that change rarely, and v-show for frequent toggling to improve performance.

Summary

Conditional rendering controls what users see based on conditions.

It helps create interactive and user-friendly pages.

Vue uses v-if and v-else directives to do this easily.