Vue.js is a progressive JavaScript framework used for building interactive user interfaces. One of its core features is directives, which allow you to extend HTML with special syntax. Directives in Vue.js provide a simple and expressive way to bind data, manage events, control rendering, and more — directly in the HTML template.
In this article, we’ll explore what Vue.js directives are, the different types of built-in directives and how to use them.
What are Directives in Vue.js?
In Vue.js, directives are special commands or attributes that start with v- and give extra functionality to HTML. Think of directives as special attributes that add reactive behaviour to your HTML. It makes it easier to build interactive and responsive pages with less code, compared to doing the same things with traditional JavaScript. It simplifies the process and makes your code cleaner and more efficient.
For example, the v-bind directive binds an attribute to an expression, and the v-if directive conditionally renders an element.
Syntax
<element v-directive="expression"></element>
- v-directive: This is the directive where the v- prefix indicates that it’s a special Vue directive.
- expression: This can be a JavaScript expression that the directive will evaluate.
Now, let us understand with the help of the example.
HTML
<html>
<head>
<title>Vue Custom Directive Example</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</head>
<body>
<div id="app">
<input v-focus placeholder="Focus will be set automatically when loaded">
</div>
<script>
// Create a new Vue instance
new Vue({
el: '#app',
// Register a custom directive called 'focus'
directives: {
focus: {
inserted: function (el) {
el.focus();
}
}
}
});
</script>
</body>
</html>
Output:
Vuejs DirectivesIn this example
- The script tag includes the Vue.js library, which is necessary to run Vue.js applications.
- A custom directive v-focus is created inside the Vue instance. This directive automatically focuses an input field when it is inserted into the DOM.
- The inserted hook is used to trigger an action when the element (input field) is added to the DOM. In this case, it focuses the input element.
- In the HTML, the v-focus directive is applied to the <input> element. When the page is loaded, Vue automatically focuses this input field.
- As soon as the page loads, the input field gets focused without requiring any user interaction, thanks to the custom directive.
Types of Vue.js Directives
Basically there are the three types of the vue directives
- Core Directives: Built-in Vue directives for common reactive behaviors.
- Event Directives: For handling user input and DOM events.
- Custom Directives: User-defined directives for custom DOM manipulations.
Core Directives
Core directives in Vue.js are the built-in directives that help manage reactive behaviors in your application. These directives are used to bind data to the DOM and conditionally render elements.
1. v-bind
The v-bind directive is used to dynamically bind an HTML attribute to an expression or a data property. It allows you to bind an element’s attribute to Vue data or computed properties.
Syntax
<img v-bind:src="imageUrl" alt="Vue logo">
Here, the src attribute of the img tag is dynamically bound to the value of the imageUrl data property.
You can also use shorthand for v-bind:
<img :src="imageUrl" alt="Vue logo">
2. v-model
The v-model directive is used for two-way data binding. It binds the value of an input field or textarea to a property in Vue's data, allowing the data to automatically update as the user types.
Syntax
<input v-model="message">
Here, the input field is bound to the message data property. Whenever the user types in the input field, message will update automatically, and vice versa.
3. v-if / v-else-if / v-else
This directive is used to conditionally render elements in the DOM. The element or component will only be rendered if the provided condition is true.
Syntax
<p v-if="isLoggedIn">Welcome back!</p>
<p v-else>Login to continue</p>
4. v-for
The v-for directive in Vue.js is used for rendering a list of items by iterating over an array or object. It simplifies the process of displaying multiple elements in the DOM by iterating over data, without needing to write repetitive code.
Syntax
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
Here, v-for loops through the items array and renders a list item (li) for each entry. The key is required for optimal performance in Vue when rendering lists.
5. v-show
Similar to v-if, the v-show directive is used to conditionally render elements, but it differs in how it does so. The v-show directive always renders the element, but it toggles the element's CSS display property based on the condition.
Syntax
<p v-show="isVisible">This is visible if isVisible is true</p>
Unlike v-if, v-show is not removed from the DOM but is simply hidden.
6. v-text
The v-text is used to update the textContent of an element.
<p v-text="message"></p>
<!-- Equivalent to -->
<p>{{ message }}</p>
7. v-html
The v-html renders raw HTML inside an element.
<div v-html="rawHtml"></div>
Security Note: Be cautious when using v-html to prevent XSS (Cross-Site Scripting) attacks.
Event Handling Directives
Event directives are used to handle user input and DOM events like clicks, form submissions, and mouse movements. These directives bind event listeners to elements.
v-on
The v-on directive is used to bind event listeners to an element. It listens for DOM events like click, input, mouseover, etc., and triggers methods when the event is fired.
Syntax
<button v-on:click="submitForm">Submit</button>
<!-- Shortcut -->
<button @click="submitForm">Submit</button>
You can also handle native DOM events like input, change, mouseover, etc.
You can also use shorthand for v-on
<input @input="updateValue" />
Modifiers with v-on
Vue provides modifiers to handle common event behavior
- .stop: event.stopPropagation()
- .prevent: event.preventDefault()
- .once: Executes only once
Example
<form @submit.prevent="onSubmit">
<button type="submit">Submit</button>
</form>
Custom Directives
Vue allows you to create your own custom directives when built-in ones are not sufficient.
Global Custom Directive
A global custom directive can be defined globally and will be available throughout your entire Vue application. It’s useful when you want to reuse a custom directive across multiple components.
Vue.directive('focus', {
mounted(el) {
el.focus();
}
});
Usage:
<template>
<input v-focus /> <!-- Automatically focused when the component is mounted -->
</template>
Local Custom Directive
Sometimes, you may only want to use a custom directive within a specific component. In that case, you can define the directive locally within the component’s directives option.
export default {
directives: {
focus: {
mounted(el) {
el.focus();
}
}
}
};
Lifecycle Hooks in Custom Directives
Custom directives support several lifecycle hooks
Hook | Description |
---|
created | Called once the directive is attached to the element |
---|
beforeMount | Before the element is inserted into the DOM |
---|
mounted | After the element is inserted into the DOM |
---|
beforeUpdate | Before the component is updated |
---|
updated | After the component is updated |
---|
beforeUnmount | Before the directive is unmounted |
---|
unmounted | After the directive is removed from the DOM |
---|
Different Vue Directives
The different Vue directives we used are listed below.
Directives | Details |
---|
v-bind | Binds an attribute to an expression. |
---|
v-if | Conditionally renders elements. |
---|
v-show | Conditionally shows/hides elements without removing them from the DOM. |
---|
v-for | Renders a list by iterating over an array or object. |
---|
v-on | Binds event listeners to DOM elements. |
---|
v-model | Two-way binding for form inputs. |
---|
v-text | Updates the textContent of an element. |
---|
v-html | Renders raw HTML inside an element. |
---|
Conclusion
By using directives like v-bind, v-model, v-if, v-for, and custom directives, you can efficiently manage dynamic behavior in the applications without complicating the codebase. Directives simplify tasks such as data binding, conditional rendering, and list rendering, which are essential for building interactive and user-friendly interfaces.
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
Top 10 Projects For Beginners To Practice HTML and CSS Skills Learning to code is an exciting journey, especially when stepping into the world of programming with HTML and CSSâthe foundation of every website you see today. For most beginners, these two building blocks are the perfect starting point to explore the creative side of web development, designing vis
8 min read
Web Development Technologies Web development refers to building, creating, and maintaining websites. It includes aspects such as web design, web publishing, web programming, and database management. It is the creation of an application that works over the internet, i.e., websites.To better understand the foundation of web devel
7 min read