Custom Directives in VueJs – Max Character for Textbox

VueJs is the new Hero in town and everyone is talking about it. And why not? It has all the features required to be a hero.
I have also been experimenting with VueJs lately and I really liked the simplicity and power of this JavaScript framework. It is slim, flexible and fast. And easy to learn of course.
I tried to create custom directives with VueJs and it turned out to be really simple. I needed a directive that can limit the number of characters typed in a text-box or text-area. Here is what I came up with:

Here is what we are going to achieve in this tutorial:

See the Pen VueJs Custom Directive by Arvind Bhardwaj (@arvind) on CodePen.

Create the directive:

var maxchars = Vue.directive("maxchars", {
  bind: function(el, binding, vnode) {
    var max_chars = binding.expression;
    var handler = function(e) {
      if (e.target.value.length > max_chars) {
        e.target.value = e.target.value.substr(0, max_chars);
      }
    };
    el.addEventListener("input", handler);
  }
});

The code takes the element el as parameter. I have added an input event listener to the element with a bit of logic to trim the string. More information about the parameters and their values can be found at VueJs official documenation.

HTML Markup

<div id="root" class="container">
  <h2>You can type only 10 characters</h2>
  <textarea v-maxchars="10" cols="50" rows="5"></textarea>
</div>

You can see that I have added v-maxchars attribute to the textarea. It will tell VueJs about the directive to be used.

The Vue App

var app = new Vue({
    el: '#root'
});

We just need to create an empty VueJs app to run the code. Nothing fany needed here.

Written by Arvind Bhardwaj

Arvind is a certified Magento 2 expert with more than 10 years of industry-wide experience.

Website: http://www.webspeaks.in/