How to create a custom Vue directive

November 26, 2018

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', { });

Directive Events Hooks

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

bind(el, binding, vnode) is once directive is attached.
inserted(el,binding, vnode) when inserted in the Parent Node.
update:(el, binding, vnode, oldVnode) when an update happened in the component.

Create the directive

The el represents the “element” in our HTML with the directive.

<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 us to get arguments from the element and use it to change the behavior.

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

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/