How to Create Custom Directives in Vue

Directives are programming constructs that specify how interpreters and compilers should process inputs for an operation. Vue directives extend the functionality of HTML elements in Vue templates, allowing direct manipulation of the DOM.

You can use directives in Vue to add event listeners, among other operations. You’ll attach extra attributes to HTML elements to use directives in your app.

4

The Structure of Vue Directives

Directives in Vue have av-prefix to distinguish them from regular HTML attributes. Thev-prefix tells the Vue compiler that the attribute is a Vue directive so it can process and apply the behavior of that directive to the HTML element.

Here’s an example that demonstrates the use of thev-showattribute to display the contents of anh2element:

Laptop on a desk showing a code editor with a dark background.

Vue.js has many more built-in directives likev-bind,v-if, andv-on, enabling you to perform tasks likedata binding,conditional rendering,event handling, and more.

Defining Custom Directives in Vue

You can define custom directives to add new, reusable functionality for your Vue.js apps. Creating custom directives requires two major steps. First, you’ll register the directive locally or globally. Then, you’ll define the directive’s behavior with lifecycle hooks.

Registering Custom Directives

You can register a custom directive in Vue locally or globally, depending on its intended scope. However, it is a more common practice to register directives globally. This ensures directives are available everywhere inside your Vue application.

You can register custom directives locally if you intend to use the custom directive inside a simple Vue component. Here’s how you can register av-changecolordirective locally:

A preview of a simple Vue app before confirmation

This code block demonstrates the local registration of a custom directive in a Vue component. It defines thev-changecolordirective as an object in camel casechangeColor.

To register your directive on a global scope, head to themain.jsfile in the root of your app directory and define it there:

A preview of a simple Vue app after confirmation

This program registers a global custom directive using theapp.directivemethod. It callsapp.directiveto register thechangecolordirective in the application and then uses theapp.mountmethod to mount the app on an HTML element with the IDapp.

you’re able to choose between the global and local options for registering custom directives based on the needs of your app.

A close-up of a hand holding up a vue.js sticker

Defining a Directive’s Behavior

you may define custom directives as objectscontaining lifecycle hooks. These lifecycle hooks define the directive’s behavior and receive the element that the directive is bound to.

Some examples of lifecycle hooks arecreated,mounted, andupdated. Each of these hooks provides functionality for interacting with the component at a specific stage.

you could use themountedlifecycle hook to access the HTML element of a component in theDocument Object Model (DOM)after the Vue.js compiler mounts the app. In contrast, theupdatedlifecycle hook can perform additional updates to components after you’ve restructured the component.

Here’s how you’re able to define an object that contains several lifecycle hooks for a Vue directive:

Custom directives may have the same behavior for themountedandupdatedhooks, with no need for other lifecycle hooks. Additionally, many custom directives you will create will require only themountedandupdatedhooks.

In such cases, it’s common to define directives as functions rather than objects with lifecycle hooks:

This code block defines a custom global directive with the stringchangecoloras the first argument. The second argument is a shorthand function defining the directive’s behavior.

As the name implies, thev-changecolordirective changes the color of any HTML element you attach it to. The directive can change the color of the HTML element randomly upon a click.

Theelparameter represents the HTML element you attached to the directive. Thebindingparameter is an object containing properties defining how to apply the directive. Thebinding.valueparameter allows you to select a default color when creating the Vue app. Thevnodeparameter contains information about the Vue.js virtual node associated with the element.

Thechangecolordirective uses aJavaScript event listenerto capture the event that triggers when you click the HTML element. Theconfirm()method displays a dialog box asking you to confirm whether you want to change the element’s color randomly.

To test the created directive, set up a Vue app similar to the one below:

Observe that this code assigns the colorredto theh2tag but no color to theh3tag. When you preview your Vue application in a browser, it should look like this:

Clicking on bothHello VueandLearn custom directives, you will notice that the tag set to red will remain red, but the tag with no value assigned to it will change to a random color.

This will happen after you confirm your choice, as demonstrated below:

Unleash Vue’s Customization Power

Custom directives provide low-level access to the DOM, allowing you to create functionality across different Vue application components, improving your app’s scalability. By following the steps in the article, you can create custom directives to ease the development process of your application.

Vue recently released version 3.3 with additional features that improve your app’s customizability and reusability. Understanding these features can take your development prowess to another level.

Get the lowdown on Vue’s latest release with this summary of important changes.

Don’t let someone else take over your phone number.

The key is not to spook your friends with over-the-top shenanigans.

My iPhone does it all, but I still need my dumb phone.

It’s not super flashy, but it can help to keep your computer up and running.

The fix was buried in one tiny toggle.

Technology Explained

PC & Mobile