Vue Directives

🔰 Vue Directives

In Vue.js, directives are special attributes provided by Vue that start with v-.

They tell Vue how to behave with the DOM (HTML elements).

👉 Example:

<p v-if="isLogin">Welcome User</p>

🔹 What are Vue Directives?

Vue directives are instructions written in HTML that control:

  • Rendering

  • Loops

  • Events

  • Data binding

  • User input handling

All directives start with v-.


🔹 Commonly Used


1️⃣ v-text

Sets the text content of an element.

<p v-text="message"></p>

Same as:

<p>{{ message }}</p>

2️⃣ v-html

Renders raw HTML inside an element.

<div v-html="htmlContent"></div>

⚠️ Use carefully (can cause XSS attacks).


3️⃣ v-if

Conditionally renders elements.

<p v-if="isLoggedIn">You are logged in</p>

4️⃣ v-else / v-else-if

Used with v-if.

<p v-if="marks >= 60">Pass</p>
<p v-else>Fail</p>

5️⃣ v-show

Shows or hides elements using CSS (display: none).

<p v-show="isVisible">Hello Vue</p>

📌 Difference:

  • v-if → removes element from DOM

  • v-show → hides element only


6️⃣ v-for

Used for looping through arrays or objects.

<ul>
<li v-for="(item, index) in items" :key="index">
{{ item }}
</li>
</ul>

7️⃣ v-bind

Binds HTML attributes dynamically.

<img v-bind:src="imageUrl">

Shortcut:

<img :src="imageUrl">

8️⃣ v-model

Creates two-way data binding (mostly used in forms).

<input v-model="username">
<p>{{ username }}</p>

9️⃣ v-on

Handles events like click, submit, etc.

<button v-on:click="sayHello">Click Me</button>

Shortcut:

<button @click="sayHello">Click Me</button>

🔟 v-once

Renders element only once.

<p v-once>{{ message }}</p>

After initial render, it won’t update.


1️⃣1️⃣ v-pre

Skips compilation for that element.

<p v-pre>{{ this will not be compiled }}</p>

🔹 Custom Directives

It also allows creating custom directives.

app.directive("focus", {
mounted(el) {
el.focus()
}
})

Usage:

<input v-focus>

🔹 Summary Table

Directive Purpose
v-if Conditional rendering
v-show Toggle visibility
v-for Looping
v-bind Attribute binding
v-model Two-way binding
v-on Event handling
v-html Render HTML
v-once One-time render

🔹 Conclusion

It make templates powerful, dynamic, and easy to read.
Mastering directives is essential before moving to components and composition API.

You may also like...