Skip to Content

Create Vue Directive With Vue Directives Examples

Vue.js provides a flexible way to handle user interactions and dynamic updates in web applications.

One of its key features, Vue directive, empowers developers to create custom behaviors and apply them directly to elements in the template.

Whether you need to manipulate the DOM, respond to events, or create reusable functionality, Vue directive have got you covered.

In this article, we will explore the process of creating Vue directives and showcase a variety of examples to inspire your own directive creations.

No products found.

Learn more by reading my longer article about Learn To Use Vue For Loop With Vue Loops Examples

Vue Directive

Vue Directive are essentially instructions that tell Vue how to manipulate the DOM (Document Object Model) when rendering the template.

What Is A Vue Directive?

Directives are special attributes that allow you to apply dynamic behavior to HTML elements.

They are essentially instructions that tell Vue how to manipulate the DOM (Document Object Model) when rendering the template.

Directives are prefixed with the v- notation and are used as attributes on HTML elements.

Vue directives provide a way to extend the functionality of HTML elements and control their behavior dynamically.

They enable you to add interactivity, apply conditional rendering, handle events, manipulate the DOM, and more.

Vue comes with several built-in directives, such as v-if, v-for, and v-bind, but you can also create custom directives to suit your specific needs.

Vue Directive Focus

Vue Directive Focus: The v-focus directive is a custom directive that can be used to automatically set the focus on an input field when the associated element is rendered.

This can be useful when you want to enhance the user experience by automatically focusing on a specific input field when a page loads.

Here’s an example of how to use the v-focus directive in Vue:

Vue Directive Focus

In this example, the v-focus directive is defined as a custom directive using Vue.directive. The inserted hook is used to handle the moment when the element is inserted into the DOM.

In the inserted hook, we call el.focus() to set the focus on the input element when it is rendered.

Check out my article about What Are Vue Lifecycle Hooks?

Vue Directive Bind

Vue Directive Bind: The v-bind directive, also known as the colon shorthand :, is a built-in directive in Vue that allows you to bind an attribute or a prop of an element to a dynamic value or an expression.

It enables you to dynamically update the value of an attribute based on data changes in the Vue component.

Here’s an example of how to use the v-bind directive in Vue:

Vue Directive Bind

In this example, the v-bind directive is used to bind the class attribute of the <p> element to the className data property.

The className value can be dynamically updated within the Vue component, and the class applied to the element will change accordingly.

The v-bind directive is also used to bind the value attribute of the <input> element to the message data property.

This allows the input field to display the value of the message property, which can be updated dynamically.

Vue Directive Inserted

Vue Directive Inserted: The inserted hook is a lifecycle hook in Vue directives that is called when the bound element is inserted into the parent DOM element.

It provides an opportunity to perform DOM manipulations or apply additional logic when an element becomes visible.

Here’s an example of how to use the inserted hook in a Vue directive:

Vue Directive Inserted

In this example, we define a custom directive called my-directive using Vue.directive.

In the inserted hook, we access the el parameter, which represents the element the directive is bound to.

We can then manipulate the element by applying CSS styles or performing any other necessary DOM manipulations.

In this case, we set the color of the element to red when it is inserted into the DOM.

Learn more about How Is Vue 3 Ref Working

Vue Directive Click Outside

Vue Directive Click Outside: The v-click-outside directive is a custom directive that allows you to detect when a user clicks outside of an element.

This can be useful when you want to trigger an action or hide an element when the user clicks outside of a specific component.

Here’s an example of how to use the v-click-outside directive in Vue:

Vue Directive Click Outside

In this example, the v-click-outside directive is defined as a custom directive using Vue.directive.

The bind hook is used to attach an event listener to the body element, which triggers the handleClickOutside method when a click event occurs outside of the bound element.

The unbind hook is used to remove the event listener when the directive is unbound.

Don´t forget to check out my article about How To Use Vue Mixin With Vue Mixins Examples

Vue Directive Hooks

Vue Directive Hooks: Vue directive hooks are an essential part of Vue.js, a popular JavaScript framework for building user interfaces.

They provide a way to manipulate the behavior and appearance of elements in the DOM (Document Object Model) by binding custom logic to specific lifecycle events.

In this brief explanation, we will explore an example of Vue directive hooks to illustrate their usage and benefits.

Let’s consider a scenario where we want to create a custom directive called “highlight” that adds a yellow background color to an element when it is clicked.

To achieve this, we can utilize the directive hooks provided by Vue.

Vue Directive Hooks

In this example, we start by defining a custom directive called “highlight” using the Vue.directive method.

Inside the directive definition object, we can specify various hooks that correspond to different lifecycle events. In our case, we focus on the bind and unbind hooks.

The bind hook is triggered when the directive is bound to an element.

It takes three parameters: el (the element the directive is bound to), binding (an object containing information about the directive), and vnode (the virtual node representing the element).

Inside the bind hook, we add an event listener to the element that changes its background color to yellow when clicked.

Vue Directive Binding Typescript

Vue Directive Binding Typescript: When working with Vue directives in TypeScript, you can provide type annotations to ensure type safety and enable better development experience.

By specifying the appropriate types for the directive’s arguments and return values, you can catch potential errors and benefit from TypeScript’s static analysis.

Here’s an example of how to define a Vue directive in TypeScript:

Vue Directive Binding Typescript

In this example, we import DirectiveBinding from the vue module to provide type annotations for the directive’s binding.

The bind, inserted, update, and unbind hooks are annotated with the appropriate types for the el and binding parameters.

This allows TypeScript to perform type checking and provide better tooling support.

Vue Directive Emit Event

Vue Directive Emit Event: In Vue directives, you can emit custom events to communicate with the parent component or trigger specific actions.

By emitting events from directives, you can provide a way for the parent component to react to certain interactions or behaviors associated with the directive.

Here’s an example of how to emit an event from a Vue directive:

Vue Directive Emit Event

In this example, we define a custom directive called custom-directive using Vue.directive. Inside the directive’s bind hook, we add an event listener to the element.

When the mouseenter event occurs, we emit a custom event named directive-event using vnode.context.$emit(). The event can carry additional data if needed.

Don´t forget to check out my article about A Guide To Vue Events With Vue Event Examples

Vue Custom Directive Typescript

Vue Custom Directive Typescript Example

Vue Custom Directive Typescript Example: In Vue.js, directives are powerful tools that allow you to attach custom behavior to elements in your templates.

They are used to manipulate the DOM, listen to events, and apply dynamic transformations to your data.

To demonstrate a Vue custom directive with TypeScript, let’s consider an example where we create a directive called uppercase.

This directive will transform the text of an input field to uppercase as the user types. Here’s how you can implement it:

Vue Custom Directive Typescript 1

In this example, we import the DirectiveBinding type from the Vue package. The mounted function is the hook that gets executed when the directive is attached to an element.

Inside this function, we add an event listener to the input element and transform the input value to uppercase.

Now, you can use this custom directive in your Vue component template like this:

Vue Custom Directive Typescript 1

Here, we import the uppercaseDirective we defined earlier and register it as a directive in the directives option of our Vue component.

The v-uppercase attribute is used to apply the directive to the input element.

The v-model directive is used for two-way data binding, binding the message data property to the value of the input field.

Vue 3 Custom Directive Typescript

Vue 3 Custom Directive Typescript Example

Vue 3 Custom Directive Typescript Example: To showcase a Vue 3 custom directive with TypeScript, let’s modify the previous example to work with Vue 3.

The implementation changes slightly due to the new composition API:

Vue 3 Custom Directive Typescript 1

The code for the custom directive remains mostly the same as before. However, the type of DirectiveBinding is now parameterized with any to allow more flexibility.

To use this directive in a Vue 3 component, the syntax changes slightly:

Vue 3 Custom Directive Typescript 2

In Vue 3, we use the defineDirective function to create a directive definition object from our custom directive.

We then register it in the directives option of our component, similar to Vue 2. The rest of the code remains unchanged.

What Is The Difference Between Directive And Component in Vue?

A directive is responsible for manipulating the DOM and adding behavior to elements.

It allows you to interact directly with the DOM, listen to events, modify attributes, and apply dynamic transformations.

Directives are typically used when you need to work with low-level DOM operations or create reusable behavior that can be applied to multiple elements.

On the other hand, a component in Vue is a self-contained unit that encapsulates both the template and the JavaScript logic associated with it.

Components provide a way to create reusable, modular building blocks for your application.

They have their own isolated state and can communicate with other components through props, events, and a centralized state management system like Vuex.

The key difference between directives and components is their focus.

Directives are primarily concerned with DOM manipulation and behavior, while components focus on creating reusable UI components with their own state and logic.

Hopefully, you now have a better understanding of how you can use Vue directive.

Understanding how you can use Vue directive will help you to tell Vue how to manipulate the DOM (Document Object Model) when rendering the template.