VuVue · Lesson 3 of 7

Template Directives

Vue's directives (`v-if`, `v-for`, `v-bind`, `v-on`, `v-model`) are the glue between your reactive data and the DOM. They're attributes that start with `v-` and get special treatment from Vue's compiler.

HTML
<template>
  <div>
    <!-- v-if / v-else-if / v-else — conditional rendering -->
    <p v-if="isLoggedIn">Welcome back!</p>
    <p v-else>Please log in.</p>

    <!-- v-show — toggles visibility (CSS display) instead of removing from DOM -->
    <div v-show="isLoading">Loading...</div>

    <!-- v-for — list rendering (always use :key) -->
    <ul>
      <li v-for="item in items" :key="item.id">
        {{ item.name }} — {{ item.price }}
      </li>
    </ul>

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

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

    <!-- v-bind (:) — bind attribute to data -->
    <img :src="user.avatar" :alt="user.name" />
    <a :href="profileUrl" :class="{ active: isActive }">Profile</a>

    <!-- v-on (@) — event listener -->
    <button @click="handleClick">Click</button>
    <input @input="handleInput" @keydown.enter="submit" />

    <!-- Event modifiers -->
    <form @submit.prevent="onSubmit">       <!-- e.preventDefault() -->
    <div @click.stop="doSomething">         <!-- e.stopPropagation() -->
    <a @click.prevent.stop="handleLink">   <!-- both -->

    <!-- v-model — two-way binding -->
    <input v-model="username" />
    <select v-model="selectedRole">
      <option value="user">User</option>
      <option value="admin">Admin</option>
    </select>
    <input type="checkbox" v-model="agreed" />
    <input type="range" v-model.number="volume" min="0" max="100" />
  </div>
</template>

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

const isLoggedIn = ref(true)
const isLoading  = ref(false)
const username   = ref("")
const agreed     = ref(false)
const volume     = ref(50)
const user = { name: "Alice", email: "alice@example.com", avatar: "/alice.jpg" }
const items = [
  { id: 1, name: "Widget", price: "$9.99" },
  { id: 2, name: "Gadget", price: "$19.99" },
]
</script>
✦ Tip
Prefer `v-show` over `v-if` for elements that toggle frequently (like a dropdown or modal) — it avoids creating/destroying DOM nodes on every toggle. Use `v-if` when the element rarely appears or has expensive child components that should not initialize until needed.