The v-if directive lets you show or hide parts of your webpage based on conditions. It helps you control what users see easily.
0
0
v-if directive behavior in Vue
Introduction
Show a login button only when the user is not logged in.
Display a warning message if a form input is invalid.
Hide a section until data has finished loading.
Toggle a menu open or closed based on user clicks.
Syntax
Vue
<element v-if="condition">Content</element>The condition is a JavaScript expression that returns true or false.
If the condition is true, the element is added to the page; if false, it is removed completely.
Examples
This paragraph shows only if
isVisible is true.Vue
<p v-if="isVisible">Hello!</p>The logout button appears only when
userLoggedIn is true.Vue
<button v-if="userLoggedIn">Logout</button>This div shows only if the
items array has one or more elements.Vue
<div v-if="items.length > 0">You have items.</div>Sample Program
This Vue component has a button that toggles a message on and off. The v-if directive shows the paragraph only when showMessage is true.
Vue
<template>
<div>
<button @click="toggle">Toggle Message</button>
<p v-if="showMessage">This message is visible!</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const showMessage = ref(false)
function toggle() {
showMessage.value = !showMessage.value
}
</script>OutputSuccess
Important Notes
Using v-if completely removes or adds elements in the DOM, which can affect performance if toggled often.
For frequent toggling, consider v-show which only hides or shows elements with CSS.
Summary
v-if controls element visibility by adding or removing it from the page.
Use it when you want to conditionally render content based on data or user actions.
Remember it affects the DOM structure, so use wisely for performance.