Creating your own custom Vue directives

Creating your own custom Vue directives

·

0 min read

Hello guys, i currently started learning Vue js and more so, i'd like to share what i'm learning while going further in Vue.

In my article today, i'd be explaining how to create a custom Vue directive. Vue directives are those reserved words that are attached to event modifiers, for example

v-on:click="" <button v-on:click="doSomething">click me</button>
v-model="" <input type="text"  v-model="myText">
v-for="" <li v-for="item in items" >{{ item }} </li>

new Vue({
  el:" #app",
  data(){
     return {
         items:['pen','book','chair'],
         myText : ""
       }
   }
})

The first directive v-on attaches a click event to the button tag which then triggers a method to actually do something.

The second directive v-model helps us create a two way binding data and makes our data option in the Vue instance reactive with the input it is placed on.

The third directive works like the traditional for loop, and mostly its used in looping through arrays or array of objects

So now we know what directives are so now let going into creating our own. There are two ways of creating a custom directive, we could either do it locally i.e inside our Vue instance or we could make it global (main.js file). For the sake of the article i'd be making it local in our vue instance. firstly in our vue instance we need to create the directive object which takes the name of the directive and also an object.

new Vue({
   el:"#app",
   directives:{
      "highlight":{

          }
     }
})

now we have the bind() method which takes in two params which are "el" and "binding" this is just referring to the Dom element and binding binds the value.

new Vue({
   el:"#app",
   directives:{
      "highlight":{
           bind( el, binding){

             }

             }
          }
     }
})

in between the bind scope we could write a logical statement which styles the element sitting in the dom.

<p v-highlight:background=" 'anyColorOfYourChoice' ">
     Lorem ipsum 
</p>

new Vue({
   el:#app,
   directives:{
      "highlight":{
           bind( el, binding){
              if(binding.arg === "background"){
                el.style.color= "black";
                el.style.background = binding.value;
             }

             }
          }
     }
})

the binding.arg simply is telling vue that if we parse an argument in the directive it should style the element to a background color of green based on the binding value, So that how we come about

v-on:click

so you can go ahead and try creating your own custom directives, till then see you in another article thanks (and keep coding).