Vue Directives

Vue Tutorial

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:

 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

v-text

Sets the text content of an element.

Same as:

v-html

Renders raw HTML inside an element.

 Use carefully (can cause XSS attacks).

v-if

Conditionally renders elements.

v-else / v-else-if

Used with v-if.

v-show

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

 Difference:

  • v-if → removes element from DOM

  • v-show → hides element only

v-for

Used for looping through arrays or objects.

v-bind

Binds HTML attributes dynamically.

Shortcut:

v-model

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

<input v-model="username">

v-on

Handles events like click, submit, etc.

Shortcut:

v-once

Renders element only once.

After initial render, it won’t update.

v-pre

Skips compilation for that element.

 Custom Directives

It also allows creating custom directives.

Usage:

<input v-focus>

 Summary Table

DirectivePurpose
v-ifConditional rendering
v-showToggle visibility
v-forLooping
v-bindAttribute binding
v-modelTwo-way binding
v-onEvent handling
v-htmlRender HTML
v-onceOne-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...