Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

Vue Conditional Rendering v if, v show, is: Tutorial, Examples, FAQs & Interview Tips

v-if vs v-show

Vue provides two ways to conditionally show elements. Choose based on how often the condition changes:

Featurev-ifv-show
DOM presenceRemoved/added from DOMAlways in DOM (display:none)
Initial render costLower (if false)Higher (always renders)
Toggle costHigher (destroy/create)Lower (CSS only)
Works with v-elseYesNo
Best forRarely toggled conditionsFrequently toggled visibility
v-if, v-else-if, v-else, v-show, Dynamic Components
<template>
  <div>
    <!-- v-if / v-else-if / v-else -->
    <div v-if="status === 'loading'">
      <span class="spinner"></span> Loading...
    </div>
    <div v-else-if="status === 'error'">
      <p class="error">{{ errorMessage }}</p>
      <button @click="retry">Retry</button>
    </div>
    <div v-else-if="status === 'empty'">
      <p>No data found.</p>
    </div>
    <div v-else>
      <!-- data is ready -->
      <ul>
        <li v-for="item in items" :key="item.id">{{ item.name }}</li>
      </ul>
    </div>

    <!-- v-show - stays in DOM, toggles display -->
    <div v-show="isMenuOpen" class="dropdown-menu">
      <a href="#">Profile</a>
      <a href="#">Settings</a>
      <a href="#">Logout</a>
    </div>
    <button @click="isMenuOpen = !isMenuOpen">Menu</button>

    <!-- <template> with v-if - no extra DOM element -->
    <template v-if="isAdmin">
      <h3>Admin Section</h3>
      <p>Only admins see this.</p>
      <button>Manage Users</button>
    </template>

    <!-- Conditional class/style -->
    <button
      :class="['btn', isActive ? 'btn-primary' : 'btn-secondary']"
      :disabled="isLoading"
    >
      {{ isLoading ? 'Saving...' : 'Save' }}
    </button>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const status = ref('loading')  // 'loading' | 'error' | 'empty' | 'success'
const errorMessage = ref('Failed to fetch data')
const items = ref([{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }])
const isMenuOpen = ref(false)
const isAdmin = ref(true)
const isActive = ref(true)
const isLoading = ref(false)

function retry() { status.value = 'loading' }
</script>
<!-- Dynamic Components - <component :is="..."> -->
<template>
  <div>
    <!-- Tab navigation -->
    <div class="tabs">
      <button
        v-for="tab in tabs"
        :key="tab.name"
        @click="currentTab = tab.name"
        :class="{ active: currentTab === tab.name }"
      >
        {{ tab.label }}
      </button>
    </div>

    <!-- Dynamic component - renders the active tab component -->
    <component :is="currentTabComponent" v-bind="tabProps" />

    <!-- KeepAlive - cache inactive components (preserve state) -->
    <KeepAlive :include="['HomeTab', 'ProfileTab']" :max="3">
      <component :is="currentTabComponent" />
    </KeepAlive>

    <!-- Dynamic component with string name (globally registered) -->
    <component :is="'BaseButton'" label="Click me" />

    <!-- Conditional component rendering -->
    <component
      :is="user.role === 'admin' ? AdminDashboard : UserDashboard"
      :user="user"
    />
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import HomeTab    from './tabs/HomeTab.vue'
import ProfileTab from './tabs/ProfileTab.vue'
import SettingsTab from './tabs/SettingsTab.vue'
import AdminDashboard from './AdminDashboard.vue'
import UserDashboard  from './UserDashboard.vue'

const currentTab = ref('home')
const user = ref({ role: 'admin', name: 'Alice' })

const tabs = [
  { name: 'home',     label: 'Home',     component: HomeTab },
  { name: 'profile',  label: 'Profile',  component: ProfileTab },
  { name: 'settings', label: 'Settings', component: SettingsTab },
]

const currentTabComponent = computed(() =>
  tabs.find(t => t.name === currentTab.value)?.component
)

const tabProps = computed(() => ({
  userId: 1,
  // other shared props
}))
</script>

Deep Dive: Conditional Rendering in Real Projects

Understanding Conditional Rendering is not just about syntax. In production applications, this topic directly affects maintainability, debugging speed, and team collaboration. Focus on readability, small reusable patterns, and predictable state flow when implementing Conditional Rendering.

A practical approach is to first implement the simplest working version, then refactor into reusable pieces (components/composables/stores) only when duplication appears. This helps keep your Vue codebase clean while avoiding over-engineering.

Common Mistakes to Avoid

  • Mixing too many responsibilities in one component instead of separating logic by concern.
  • Skipping meaningful naming for variables, emits, and component props.
  • Ignoring edge cases like empty data, loading states, and error handling.
  • Optimizing too early before measuring real bottlenecks in browser devtools.
  • Not creating small test scenarios to validate behavior after each change.

Mini Practice Checklist

  1. Build a small demo focused only on Conditional Rendering.
  2. Add one edge case (empty/loading/error) and handle it cleanly.
  3. Refactor repeated logic into a reusable function/composable.
  4. Add clear comments only where logic is non-obvious.
  5. Verify behavior with manual testing and Vue Devtools.
Key Takeaways
  • This chapter on Conditional Rendering focuses on practical Vue 3 patterns used in real projects.
  • Prefer the Composition API with script setup for cleaner and more scalable component logic.
  • Keep components focused and move reusable logic into composables when complexity grows.
  • Use Vue Devtools to inspect component state, props, emits, and performance during development.
  • Write small experiments for each concept before applying it in production code.
  • After finishing this chapter, continue to the next related topic in the Vue roadmap.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.