In Vue.js, directives are special tokens in the markup that tell the library to do something to a DOM element.
They are prefixed with v- and are Vue-specific attributes added to HTML elements or components.
Directives are used to apply dynamic behaviour to the DOM, such as manipulating the DOM attributes, controlling the visibility of elements, rendering lists, and many more.
Here's an overview of directives and its types in Vue.js:
The v-bind directive, abbreviated as ":" is used to bind HTML attributes to Vue.js data.
It dynamically binds an attribute's value to an expression, allowing us to reactively update the attribute when the data changes.
<img v-bind:src="image-url" />
<p :class="{ 'text-danger': hasError }"></p>
Attribute and Class Binding: v-bind (Shorthand :): Binds an attribute or class to an expression.
<input v-model="firstName" type="text" />
The v-model directive is used to create two-way data binding on form input elements.
It binds the value of an input field to a Vue.js data property, allowing changes in the input field to update the data property and vice versa.
<ul> <li v-for="city in cities" :key="city.id"> {{ city.name }} </li> </ul>
The v-for directive is used to render a list of items based on an array.
<div v-if="isLoggedIn" >Welcome, {{ firstName }} </div> <div v-else > Please signin before using our services. </div>
It iterates over each item in the array and renders a template for each item.
<div v-show="isLoggedIn" > Sign Out </div>
The v-if directive is used to conditionally render an element based on a truthy value.
The v-else directive is used to define the alternate condition when v-if evaluates to false.
<button v-on:click="handleIncrementCount" > Increment count </button> or // v-on can be shortened to @ for event handling. <button @click="handleIncrementCount"> Increment count </button>
The v-show directive is similar to v-if, but it toggles the CSS display property of the element instead of rendering or removing it from the DOM.
It is often used for toggling visibility.
The "v-on" directive, shorthand as @, is used to attach event listeners to DOM elements.
It allows us to listen to DOM events and execute methods or expressions when those events occur.
Directives in Vue.js provide a powerful way to add dynamic behaviour to HTML elements and components. It enables interactivity and reactive user interfaces by handling data binding, conditional rendering, list rendering, event handling, and more.