Create Custom Directives with Vue

Vue directives allow us to make low-level DOM access on elements also it’s that you have already used in Vue such as “v-model”, and “v-if” the build-in directives shipped with core. The Vue directives will have a prefix with “v-” when used, in addition, it also allows us to make custom directives. 

Custom directives with bind value

Here we register a local custom directive it only works in that component. The directive is called “textColor” which will apply the style color from the assigned value to the component element. To use the directive we can call it with the prefix “v-” and the directive name in the kebab case or the registered case (In this case camelCase).

In the <BaseButton /> component

<template>
  <button>Click</button>
</template>

A parent using this component

<template>
  <div>
    <BaseButton v-text-color="'blue'" />
  </div>
</template>

<script>
import BaseButton from '@/components/BaseButton.vue';

export default {
  components: {
    BaseButton,
  },
  directives: {
    textColor: {
      bind: function (el, binding) {
        el.style.color = binding.value;
      },
    },
  },
};
</script>

The render DOM 

<button style="color: blue;">Click</button>

Custom directives with the argument

What comes after the “:” sign is an argument in this case we used it to know the text or background color to apply the color, based on the argument. In the bind function, we check to apply style property based on the argument.

In the <BaseButton /> component

<template>
  <button>Click</button>
</template>

A parent using this component

<template>
  <div>
    <BaseButton v-color:text="'blue'" />
    <BaseButton v-color:bg="'red'" />
  </div>
</template>

<script>
import BaseButton from '@/components/BaseButton.vue';

export default {
  components: {
    BaseButton,
  },
  directives: {
    color: {
      bind: function (el, binding) {
        const styleProperty = {
          bg: 'backgroundColor',
          text: 'color',
        };
        el.style[styleProperty[binding.arg]] = binding.value;
      },
    },
  },
};
</script>

The render DOM

<button style="color: blue;">Click</button>
<button style="background-color: red;">Click</button>

Registered custom directives globally

To register custom directives globally instead of locally we can declare them in the main.js with the Vue instance.

Vue.directive('textColor', {
  bind: function (el, binding) {
    el.style.color = binding.value;
  }
})