Interpolation and the main directives


🧩 1. Interpolation ({{ }})

Interpolation lets you insert dynamic data into your HTML templates.

✅ Example:

<template>
  <h1>Hello, {{ name }}!</h1>
</template>

<script setup>
const name = 'Vue Learner'
</script>

🧠 Output:

Hello, Vue Learner!

You can also use JavaScript expressions inside interpolation:

<p>{{ 2 + 2 }}</p>          <!-- 4 -->
<p>{{ name.toUpperCase() }}</p> <!-- VUE LEARNER -->

🟢 2. v-if — Conditional Rendering

Use v-if to show or hide elements based on a condition.

✅ Example:

<template>
  <p v-if="isLoggedIn">Welcome back!</p>
  <p v-else>Please log in.</p>
</template>

<script setup>
const isLoggedIn = false
</script>

🧠 Output:

Please log in.

👉 v-show is similar but toggles CSS display instead of adding/removing the element.


🟠 3. v-for — Looping Over Data

Use v-for to render a list.

✅ Example:

<template>
  <ul>
    <li v-for="(fruit, index) in fruits" :key="index">
      {{ index + 1 }}. {{ fruit }}
    </li>
  </ul>
</template>

<script setup>
const fruits = ['Apple', 'Banana', 'Cherry']
</script>

🧠 Output:

1. Apple
2. Banana
3. Cherry

Always add a :key for performance and stable reactivity.


🔵 4. v-bind — Binding Attributes

v-bind dynamically binds an attribute or prop to a value.

✅ Example:

<template>
  <img v-bind:src="imageUrl" alt="Dynamic Image">
  <!-- shorthand -->
  <img :src="imageUrl" alt="Dynamic Image">
</template>

<script setup>
const imageUrl = 'https://vuejs.org/images/logo.png'
</script>

🧠 Output:
Displays the Vue logo.

You can also bind classes and styles dynamically:

<p :class="{ active: isActive }">Active status</p>
<p :style="{ color: textColor }">Colored text</p>

🟣 5. v-model — Two-Way Data Binding

v-model creates two-way data binding between a form input and your data.

✅ Example:

<template>
  <input v-model="message" placeholder="Type something">
  <p>You typed: {{ message }}</p>
</template>

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

const message = ref('')
</script>

🧠 Explanation:

  • Typing in the input updates message
  • Updating message updates the input value

🔴 6. v-on — Event Handling

Use v-on to listen for DOM events (like click, input, etc.).

✅ Example:

<template>
  <button v-on:click="count++">Clicked {{ count }} times</button>
  <!-- shorthand -->
  <button @click="count++">Clicked {{ count }} times</button>
</template>

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

const count = ref(0)
</script>

🧠 Output:
Each click increases the counter.

You can also call a function:

<button @click="sayHello">Say Hello</button>

<script setup>
function sayHello() {
  alert('Hello from Vue!')
}
</script>

🧠 Summary Table

DirectivePurposeShorthandExample
v-ifConditional rendering—<p v-if="ok">OK</p>
v-forLooping lists—<li v-for="item in list">
v-bindBind attributes:<img :src="url">
v-modelTwo-way data binding—<input v-model="name">
v-onEvent listener@<button @click="doSomething">

Leave a Reply