Vue.js Lesson 3: Template Syntax

💚 Vue.js CourseLesson 3 of 10 · 30% complete

Vue templates are HTML with special directives (v-) and mustache syntax ({{ }}) for binding data.

Mustache & v-bind

<template>
  <!-- Mustache: display data -->
  <h1>{{ title }}</h1>
  <p>{{ 2 + 2 }}</p>
  <p>{{ message.toUpperCase() }}</p>
  
  <!-- v-bind: bind HTML attributes -->
  <a :href="url">Link</a>
  <img :src="imageUrl" :alt="imageAlt" />
  <div :class="isActive ? 'active' : ''">
  
  <!-- v-html: render HTML (careful with XSS!) -->
  <div v-html="htmlContent"></div>
</template>

v-if & v-for

<template>
  <!-- v-if, v-else-if, v-else -->
  <div v-if="user.role === 'admin'">Admin Panel</div>
  <div v-else-if="user.role === 'editor'">Editor Panel</div>
  <div v-else>Regular User</div>
  
  <!-- v-show: toggles display (element stays in DOM) -->
  <div v-show="isVisible">Always rendered, hidden with CSS</div>
  
  <!-- v-for: render lists (key is required!) -->
  <ul>
    <li v-for="item in items" :key="item.id">
      {{ item.name }} — ${{ item.price }}
    </li>
  </ul>
  
  <!-- v-for with index -->
  <div v-for="(item, index) in items" :key="index">
    {{ index + 1 }}. {{ item.name }}
  </div>
</template>

v-model: Two-Way Binding

<template>
  <!-- v-model syncs input ↔ data automatically -->
  <input v-model="text" placeholder="Type here..." />
  <p>You typed: {{ text }}</p>
  
  <!-- Works with select, checkbox, textarea too -->
  <select v-model="selected">
    <option v-for="opt in options" :key="opt" :value="opt">{{ opt }}</option>
  </select>
  <p>Selected: {{ selected }}</p>
</template><pre style="background:#0d1117;border:1px solid rgba(255,255,255,.08);border-radius:10px;padding:20px;overflow-x:auto;margin:16px 0;"><code style="font:14px/1.7 'Fira Code',monospace;color:#e6edf3;white-space:pre;">&lt;script setup&gt;
import { ref } from "vue";
const text = ref("");
const selected = ref("vue");
const options = ref(["vue", "react", "angular"]);
&lt;/script&gt;</code></pre>

🏋️ Practice Task

Build a product catalog. Array of 5 products (name, price, stock). Use v-for to render each. Use v-if to show “In Stock” or “Out of Stock” based on stock. Add a search input with v-model that filters the displayed products.

💡 Hint: Filter: const filteredProducts = computed(() => products.value.filter(p => p.name.toLowerCase().includes(search.value.toLowerCase())))

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *