Custom Vue directives

Custom Vue directives

What are custom directives?

A directive is generally some special token in the markup that tells the library to do something with a DOM element. Vue has its own predefined directives but what if we want to do something or perform some action that is not yet explicitly defined with any Vue directive. Vue allows you to create your own custom directive where we can define the custom action we want to suit the individual needs of the project.

Syntax for custom directive

To create a new custom directive, call the directive() function on the Vue instance. This function accepts two arguments: the name of the directive and an object with all the “hooks” related to the life cycle of the Vue instance.

to be more clear:

Directive name

Whatever name we choose for the custom directive, Vue will automatically prefix the directive name with v-, so the template can access your directive as v-directive_name.

Useable hooks

As part of the object that is passed as the second parameter of the directive() method, the so-called “hooks” on which the directive is “hooked” and activated. Here is a list of available hooks in ver. 3.0:

  • created: Called before the attributes or event listeners of the bound element are applied. This is useful in cases where the directive needs to attach event listeners that must be called before the normal v-on event listeners.
  • beforeMount: Called when the directive is first attached to an element and before the (mounted) parent component is attached.
  • mounted: Called when the application is mounted (mounted) for the element.
  • beforeUpdate>: Called before the VNode containing the component is updated.
  • updated: Called after updating the VNode component.
  • beforeUnmount: Called before the parent component is “unmounted” from the element.
  • Unmounted: Called only once, when the directive is unmounted from an HTML element.
Example

See the Pen
Custom Vue Directives
by Web Programming (@chos)
on CodePen.