Vue Directives: v-if, v-show, v-for

Vue Directives: v-if, v-show, v-for

Vue's built-in directives are special attributes that apply reactive behaviour to rendered elements.

Conditional Rendering — v-if / v-else-if / v-else

<div v-if="role === 'admin'">Admin Panel</div>
<div v-else-if="role === 'editor'">Editor Dashboard</div>
<div v-else>Welcome, Guest</div>

v-show — Toggle Visibility

<!-- element stays in the DOM but display:none is toggled -->
<div v-show="isVisible">Visible when true</div>

v-if vs v-show: use v-if when the condition rarely changes (adds/removes from DOM); use v-show when toggling frequently (cheaper re-renders).

List Rendering — v-for

<ul>
  <li v-for="item in items" :key="item.id">
    {{ item.name }}
  </li>
</ul>

<!-- with index -->
<li v-for="(item, index) in items" :key="item.id">
  {{ index + 1 }}. {{ item.name }}
</li>

<!-- iterate over object properties -->
<div v-for="(value, key) in user" :key="key">
  {{ key }}: {{ value }}
</div>

Always provide a unique :key when using v-for — it helps Vue efficiently patch the DOM when the list changes.