Performance: Why conditional rendering matters
Conditional rendering affects how many elements the browser must create and manage, impacting page load and interaction speed.
<template> <div v-if="isVisible">Content</div> </template> <script setup> import { ref } from 'vue' const isVisible = ref(false) </script>
<template> <div v-show="isVisible">Content</div> </template> <script setup> import { ref } from 'vue' const isVisible = ref(false) </script>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| v-show toggling visibility | Element always in DOM | Triggers reflow on toggle | Paint triggered on toggle | [X] Bad |
| v-if conditional rendering | Element added/removed as needed | Reflow only when element changes | Paint only when element changes | [OK] Good |
isVisible is true?v-if to conditionally render elements based on a boolean.v-if="isVisible" correctly binds the condition to show the paragraph only if true.<template>
<div>
<p v-if="showMessage">Hello User!</p>
<p v-else>Please log in.</p>
</div>
</template>showMessage is false?showMessage is false, the v-if block is skipped and v-else block runs.v-else paragraph with text "Please log in." will be shown.<template>
<div>
<p v-if="isActive">Active</p>
<p v-else-if="isPending">Pending</p>
<p v-else>Inactive</p>
</div>
</template>isActive and isPending are both false?v-else runs.isActive and isPending false means v-else block should show 'Inactive'.v-for loop to achieve this?v-if on the same element as v-for filters which items render.<ul>
<li v-for="user in users" v-if="user.active">{{ user.name }}</li>
</ul> applies v-if="user.active" on the <li> with v-for, showing only active users.Pass the test and this pattern moves unknown