Directives in Vue.js: Usage and Examples

Directives in Vue.js allow you to apply special behaviors to elements in the DOM. They are prefixed with the v- syntax and are used to manipulate the DOM, handle events, conditionally render elements, and more. Vue.js provides several built-in directives such as v-if, v-for, v-bind, and v-on, which cover a wide range of common use cases.

Here are some common directives in Vue.js:

 

1. v-if Directive: This directive is used to conditionally render an element based on a condition.

Example:

<div v-if="isShow">This element is only displayed if isShow is true.</div>

 

2. v-for Directive: This directive is used to iterate over an array or an object and create corresponding elements.

Example:

<ul>
  <li v-for="item in items">{{ item }}</li>
</ul>

 

3. v-bind Directive: This directive is used to bind the value of an expression to an attribute or a property of an element.

Example:

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

 

4. v-on Directive: This directive is used to listen to and handle events on an element.

Example:

 <button v-on:click="handleClick">Click me!</button>

 

5. v-model Directive: This directive creates a two-way binding between an input element and a data property.

Example:

<input v-model="message">

 

These are just some basic directives in Vue.js. You can also create your own custom directives to perform specific behaviors in your Vue.js application.