How to create a custom Vue directive

November 26, 2018

Cooking your Vue Directive Cooking your 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', { });

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 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 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.



Originally published at danywalls.com on November 26, 2018.

Dany Paredes

Hi, I'm Dany Paredes, few years ago I was working with .NET, but in my last years I have been focusing in Javascript using Vue , Angular or React. You can read more in Twitter or Github.