How to create a custom Vue directive

Vue allows create custom directives, modify our HTML elements and behavior, you can recognize easy because the first letter is v- like v-text or v-html.

Create a Directive

The directives can register global or scoped. Every directive needs the name as the first parameter and object configuration as the second parameter.

Vue.directive('transparent'); <h2 v-transparent>1,500</h2>

Directive Events Hooks

The directives contain a few events where we can attach and every one has a stage.

bind(el, binding, vnode) is once directive is attached.

inserted(el,binding, vnode) when inserted in Parent Node.

update:(el, binding, vnode, oldVnode) when an update happened in the component.

Object configuration

The el represents the “element” in our HTML with the directive and using the event hook bind it can change or modify the behavior of the HTML element.

<h2 v-transparent>My Power</h2>

Vue.directive('transparent', { bind(el,binding,vnode) { el.style.opacitiy = "0,5"; } });

Passing parameters

The binding is an option to send values from the element to the directive.

<h2 v-transparent="0.1">1500</h2>

Vue.directive('transparent', { bind(el,binding,vnode) { el.style.opacitiy = binding.value } });

Passing arguments

binding.args allow to get arguments from the element and use it to change the behavior.

<h2 v-transparent:es="0.1">1500</h2> Vue.directive('transparent', { bind(el,binding,vnode) { el.style.opacitiy = "0,5"; if(binding.arg == "es") { const formated = "€${el.textContent}" el.textContent = formated; } } });

So there you have it, I have shown you how to create directives and use them. Now go use this newfound knowledge to make something amazing.

https://jsfiddle.net/danyparedes/vcnLpu1r/

#vue