Directives in Vue.js

Manav Pandya  Print   20 min read  
15 May 2019
 
Intermediate
144

Directives are used to modify the behavior of our HTML elements which resides into the DOM. In other words, we can say that directives are one of the important parts for the Vue and it is used just like an HTML element’s attribute added along with any HTML elements into the Vue template. This is called the special attribute by which we can perform the various kind of actions based on the directive function implementation. There are tons of in-built directives supported into the VueJs but we can also create our custom directive in order to perform the required behavior using the HTML element.

Syntax to use Directives in Vuejs

In order to create and use the different directives, we need to follow the directive pattern which is explained below. In Vue, we need to use “v-” prefix along with the directive name like this.

 
 <element prefix-directiveId="[arg:] ( keypath | expression ) [filters...]">
 // code
 </element>

As you can see into the above syntax, we have “prefix” followed by the directive name or id which we can use to identify the type of directive, below is the simple example of the v-model directive which is in-built directive provided with the Vue.

 
 <template>
 <div class="hello">
 <h1>{{ message }}</h1>
 <div>
 <input v-model="fullName" />
 </div><br />
 <div>
 Your Full Name Is : {{ fullName }}
 </div>
 </div>

</template>

<script>
export default {
 name: "Model",
 data() {
 return {
 message: "v-model Directive in VueJs",
 fullName: ""
 };
 }
};
</script>

Here in the above example, we have a variable called “fullName” and using this variable, we are going to use its value, and it means we are trying to implement two-way data binding. And by using the v-model directive, the value of the full name will be synced based on the change event of the input. This is how we can use the directives with the “v-” prefix followed by the directive name.

Types of Directives in Vue

So far, we have learned that what is directive and how to use the directive into our Vue application. Vuejs contains the list of directives, which we can use to perform various actions based on different situations. Below are the different directives supported into the Vue along with the appropriate examples.

v-show directive

the v-show directive in Vuejs is used to show or hide the different HTML elements conditionally. Just like the toggle effect, if we want to hide or show something based on the specific flag, then we can use this directive in order to achieve hide/show function.

Syntax
 <element v-show="flag/condition">
 // content
</element>
 
Example
<template>
<div class="hello">
 <h1>{{ message }}</h1>
 <div v-show="isVisible">
 <h1>This Is v-show Example</h1>
 </div>
</div>
</template>

<script>
export default {
name: "Show",
data() {
 return {
 message: "v-show Directive in VueJs",
 isVisible: true
 };
}
};
</script>

Into the above example, we have a boolean flag “isVisible” with the default value set to the true and based the flag value, the specific div element will be shown or hidden based on the boolean value. After running the above example, we can see the output like this.

v-bind directive

the v-bind directive is used to bind the value from the script to template or else we can say that v-bind is used to bind the value from the component logic to the HTML template. We can also call it “one-way data binding” because it binds the values from the business logic to the template like the value of a label, classes, styles, arrays, objects and image source.

Syntax
 <element v-bind:property="value">
 // content
 </element>
 
Example
 
 <template>
 <div class="hello">
 <h1>{{ message }}</h1>
 <div>
 <img v-bind:src="value1" /> 
 <img v-bind:src="value2" />
 </div>
 </div>
 </template>
 
 <script>
 export default {
 name: "Bind",
 data() {
 return {
 message: "v-bind Directive in VueJs",
 value1:
 "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT4-_9RcAcEzGNJwggrEybw0eGKz9WL1tTT5FMp5RC4SGQUmOOs",
 value2:
 "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSiLWmP_PWT8i0wDoSDcpumNyoNmb-tjfffWz3bKx-rNLY60VdscA"
 };
 }
 };
 </script>

In the above example, we are trying to bind the image source using the v-bind directive. For that, we have used two different variables which provides the image URL and it will be bind to the src property of image element using the v-bind directive. But to keep in mind that it won’t work two ways and value will not be reflected vice-versa.

v-model directive

We have seen the example of v-model, into the introductory part that how to use this directive. Basically, the v-model directive is used to bind the value of a script to the Vue template, and it will be a “two-way data binding” in other terms. Below is the simple example in which we are getting the value of a textbox element and showing the value at a time.

 
 <template>
 <div class="hello">
 <h1>{{ message }}</h1>
 <div>
 <input v-model="fullName" />
 </div><br />
 <div>
 Your Full Name Is : {{ fullName }}
 </div>
 </div>

</template>

<script>
export default {
 name: "Model",
 data() {
 return {
 message: "v-model Directive in VueJs",
 fullName: ""
 };
 }
};
</script>

v-for directive

the v-for directive in Vuejs is used to iterate over the below list of items.

  • Arrays

  • Objects

  • Array of objects

  • A specific range of the integer/numbers

Quiet as many times, we need to perform the iteration based on the different functional requirements. For such requirements, we can use v-for directive which is similar to for loop which we have used in other different programming languages.

Syntax
 
<element v-for="(value, key) in array_object">
 //content
 </element>
Example
 
 <template>
 <div class="hello">
 <!-- <h1>{{ message }}</h1> -->
 <h3
 v-for="(value, key) in values"
 v-bind:key="value"
 >
 {{ key }} : {{ value }}
 </h3>
 </div>
</template>

<script>
export default {
 name: "Loop",
 data() {
 return {
 message: "v-for Directive in VueJs",
 values: [
 "Value 1",
 "Value 2",
 "Value 3",
 "Value 4",
 "Value 5",
 "Value 6",
 "Value 7",
 "Value 8",
 "Value 9",
 "Value 10"
 ]
 };
 }
};
</script>

Here in the above example, we have a list of values as an Array, and also going to iterate the items using the v-for. the v-for directive will iterate over the Array until it reaches to the last element of an array and will print the appropriate values. This is how we can iterate over the arrays, objects and so on using the v-for directive.

v-if, v-else and v-else-if directives

These all the conditional rendering directive which is used to add or remove element based on the specific condition.

v-if

This directive is used to render the element if the condition provided will be evaluated to be true.

Syntax
 
 <element v-if="variable/ (true/false) / expression">
 // content
 </element>
 

v-else

This directive is used to render the element if the v-if directive will be evaluated to false along with the content.

Syntax
 
 <element v-else>
 // content
 </element>

But to keep in mind that we don’t need to pass any expression or condition because it will be rendered if the if condition evaluated false then the v-else portion will be rendered by default.

v-else-if

the v-else-if directive is used to render an element if we have multiple conditions to be evaluated but need to compare each and every condition for the batter rendering element. It can be used along with the other directives like v-if and v-else.

Syntax
 
 <element v-else-if="varible/ (true/false) / expression">
 // content
 </element>
Example of simple v-if and v-else
 
 <template> 
 <div class="hello">
 <h1>{{ message }}</h1>
 <div v-if="myValue < 10">
 <h1>Number is less than 10</h1>
 </div>
 <div v-else>
 <h1>Number is equal to 10</h1>
 </div>
 </div>
 </template>
 
 <script>
 export default {
 name: "Show",
 data() {
 return {
 message: "v-if and v-else Directive in VueJs",
 myValue: 10
 };
 }
 };
 </script>
 
 <!-- Add "scoped" attribute to limit CSS to this component only -->
 <style scoped>
 </style>

In this example, we have one data variable which is called “myValue” with the 10 as the default value. So based on the variable, we are going to evaluate the condition whether the value is greater than 10 or equal. After running the above example, we can see the output like this.

Example of simple v-if, v-else-if and v-else
 
 <template>
 <div class="hello">
 <h1>{{ message }}</h1>
 <div v-if="myValue < 10">
 <h1>Number is less than 10</h1>
 </div>
 <div v-else-if="myValue > 10">
 <h1>Number is greater than 10</h1>
 </div>
 <div v-else>
 <h1>Number is equal to 10</h1>
 </div>
 </div>
 </template>
 
 <script>
 export default {
 name: "Show",
 data() {
 return {
 message: "v-if, v-else-if and v-else Directive in VueJs",
 myValue: 10
 };
 }
 };
 </script>
 
 <!-- Add "scoped" attribute to limit CSS to this component only -->
 <style scoped>
 </style>

In this example, we have the same data variable “myValue”, and based on the different condition, we are going to render a different message. This is how we can use if, else if and else conditional directives to evaluate the different expression. After running the above example, we can see the output like this.

v-text directive

the v-text directive in Vue is very similar to the interpolation and v-text is used to bind the value of the data variables into the Vue template. We can also call it as “one-way data binding” because it binds the value to the template element directly.

Syntax
 <element v-text="data_variable">
 // content
 </element>
Example
 <template>
 <div class="hello">
 <h1>{{ message }}</h1><br />
 <h1 v-text="message"></h1>
 </div>
 </template>
 
 <script>
 export default {
 name: "Show",
 data() {
 return {
 message: "v-text Directive in VueJs",
 };
 }
 };
 </script>
 
 <!-- Add "scoped" attribute to limit CSS to this component only -->
 <style scoped>
 </style> 

Here in this example, we have one data variable called “message” which contains the static message. In order to use the “message” value, we can use two different approaches.

  • String interpolation

  • v-text

In this example, we have used two of the methods which show the static message into the template or we can say it binds the data variable’s value into the Vue template. When we run the above example, the output will be like this.

So far, we have learned about the different directives which we can use into our project to play around the different HTML dom elements behaviour like showing or hiding elements, conditional rendering, element iteration etc. These all are the in-built directives provided by the Vue, but if we can also create our custom directive as well.

Custom Directive

We have seen the various types of in-built directives for the different requirements, but do you think that these directives are well suited for all our functional requirements? I don’t think so, because sometimes it may happen that we want some behaviour which cannot be fulfilled by those in-built directives. Then Custom Directives comes into the picture which is used to create the custom behaviour of an HTML element based on our requirement.

How to create the Custom Directive

Now we know the requirement of the custom directive, but we may think that how to create it. We can create any custom directive using the separate section into the <script> section which is called “directives” section. Below is the normal directives section into the Vue file.

 
 7lt;script>>
 export default {
 name: "Custom",
 data() {
 return {
 message: "Custom Directive in VueJs"
 };
 },
 directives: {
 // custom directive functions
 }
 };
 </script>

As you can see into the above syntax, we have a separate section for “directives” where we can create and implement different custom directives. Now let’s see the simple example for the custom directive to change the font size based on the mouse over and mouse out events for the label element.

Example
 <template>
 <div class="hello">
 <h1>{{ message }}</h1>
 <div>
 <label v-fontSize>Hover On ME !!!</label>
 </div>
 </div>
 </template>
 
 <script>
 export default {
 name: "Custom",
 data() {
 return {
 message: "Custom Directive in VueJs"
 };
 },
 directives: {
 fontSize: {
 bind(el, binding) {
 el.onmouseover = function() {
 el.style.fontSize = "50px";
 };
 el.onmouseout = function() {
 el.style.fontSize = "15px";
 };
 }
 }
 }
 };
 </script>
 
 <!-- Add "scoped" attribute to limit CSS to this component only -->
 <style scoped>
 </style>

In the above example, we are trying to change the font size of an <label> element using the custom directive. For that, we have created a custom directive named “font-size”.

 
 fontSize: {
 bind(el, binding) {
 el.onmouseover = function() {
 el.style.fontSize = "50px";
 };
 el.onmouseout = function() {
 el.style.fontSize = "15px";
 };
 }
 }

Which accept the complete HTML element and change the styles of an element i.e. font size based on the two different events.

  • Onmouseover()

  • Onmouseout()

This is how we can write the custom logic to change the behaviour of any HTML element based on our functional requirement. After running the above example, we can see the output like this.

Before the hover event

After the hover event

Hook Functions

In our previous example, we have created a Custom Directive inside the “directive” section of a script. But with that, we have also used one term “bind”, what does it mean, well its nothing but a kind of Hook Function which is used to trigger the specific action based on the Hook cycle. It is just like a different Hooks lifecycle method but has different methods in the context of directives. Let’s see the list of Hooks function for the directives.

  • inserted(..element, ..binding, ..vnode): This hook function will be triggered whenever any directive bounds to the specific element once in a while. By using this hook function, we can perform various initial functions which need some onload kind of things.

  • inserted(..element, ..binding, ..vnode) :Called when the component or element is inserted into its parent node. It may not be in the DOM yet.

  • update(..element, ..binding, ..vnode, ..oldVnode) : It is called when the containing component has updated but just before its children will be updated.

  • componentUpdated(..element, ..binding, ..vnode, ..oldVnode) : It is called when the containing component has updated but after its children will be updated.

  • unbind(..element, ..binding, ..vnode) :It is called when any directive is going to unbound from the component or element and it will trigger only once a time.

All these are the Hook Functions which can be applicable while binding the directive to the different HTML elements. Let’s see one example of using any Hook Function listed above and see how it works.

Example
 <template>
 <div class="hello">
 <h1>{{ message }}</h1>
 <label v-onHover>This is Label with Custom Directive</label>
 </div>
 </template>
 
 <script>
 export default {
 name: "HookExample",
 data() {
 return {
 message: "Hook Function in VueJs"
 };
 },
 directives: {
 onHover: {
 bind(el, binding) {
 alert("Bind Hook Function Called Once");
 }
 }
 }
 };
 </script>
 
 <!-- Add "scoped" attribute to limit CSS to this component only -->
 <style scoped>
 </style>

Here in the above example, we have one simple <label> element along with the custom directive called “onHover”. So whenever we execute the above file, we will get the simple alert box along with the message that “bind” will be called once whenever our directive binds to the HTML element. After running the above example, we can see the output like this.

So whenever we run our file, we can see the output like this which shows the message, same way we can use different hook function based on the different functional requirement.

Directive Hook Arguments

Every hook function allows us to provide the various arguments for batter configuration for the directives. Not every argument are compulsory except “el” which is used to pass the complete HTML element to the Hook Function. Below is the complete list of arguments provided to Hook Functions.

element

The main HTML element to be bind along with the directive. When we try to console it, we can see that the complete HTML element will be returned.

binding

Basically, this is an Object which contains the various properties which we can use into our binding configuration setting. Below is the complete list of supported arguments.

  • binding. name The appropriate name of our custom directive.

  • binding.value: The value of a JavaScript expression passed to the directive. We can process “value” based on the custom behaviour like changing the size of text, color, and other settings.

  • binding.oldValue: Contains the previous value of the directive, but only provided an update and componentUpdated hook functions.

  • binding.expression: This is the value expression represented as a string. For example directive (v-directive= {25 * 25}) then the expression will be evaluated “25 * 25” into the directive function body.

  • binding.arg –: This is the argument which will be passed to the directive. For example the directive (v-directive: URL=” value”) then: URL will act as a binding argument.

  • binding .modifiers: It is the object which contains any modifiers passed to the directive as Boolean values. For example (v-XYZ.hi1.hi2) then value of the modifiers would be {hi1: true, hi2: true}

    vnode

    This is a virtual node used by Vue’s renderer engine or compiler. Its batter to understand that when we should use this in our functional requirement.

    oldVnode

    The previous version of the above Vnode. And it is only available in the update hooks in order to get the older value of a specific node.

    Here we have seen the different arguments to be passed along with the directive, which further will be processed based on the custom behaviour for batter directive configuration.

    Empty Directive

    Version 0.12 supports the Empty directive which doesn’t accept any argument. It means Empty Directive will ignore if there are any arguments provided and also ignore its value. By default, there are two types of empty directives are supported which are listed below.

    v-pre

    It will ignore each and every parent and child element and does not allow its content to be compiled.

    v-cloak

    This property remains on the element until the associated ViewModel finishes its compilation.

    It’s combined with the different CSS rules such as [v-cloak] {display: none}, this directive can be used to hide un-compiled mustache bindings until the ViewModel is ready for the execution.

    Example
     <div v-pre>
     Hello World
     </div>
    

    The content inside the <div> element will be ignored for the compilation but it renders its content.

    Read More Articles Related to vue

    Summary

    Directives play an important role in VueJs to apply and update the behaviour of the different HTML element. So far in this article, we have learned different aspects of Directives which are listed below.

    • What is the Directive?

    • How to use Directive in Vue?

    • Different types of In-built Directive

    • How to create Custom Directive

    • Different Hook Functions are supported

    • Arguments provided to the Hook Functions

    • Empty Directive

      I hope we have learned Directive in a simpler manner, I would recommend to just try it out and see how it help to make our development life easier.

Learn to Crack Your Technical Interview

 
Learn to Code

Start your journey today to learn coding!


Because learning to code is the first step and foreward to advance your career.


 GET STARTED NOW 

+
+
Accept cookies and close this message