Vue Js Directives Step By Step With Examples 2020

So today we are going to see some most used Vue Js directives.


Vue Directive is a special markup that tells the library to do something to DOM(document object model) element.


There are so many Vue Js Directives. Lets explore this


It is used to do an action on some dom element when click or change or blur event happens. It is simmilar to javascript's "onclick / onblur /onchange". In VueJs if you want to do something on click you will code it like this

 //To do something on click
<div v-on:click='functionName()'></div>
//To do something on change
<div v-on:change='functionName()'></div>
//To do something on blur
<div v-on:blur='functionName()'></div>


This is the conditional rendering in Vue Js. Check this example.

 <p v-if='name=="roger"'>Roger</p>
<p v-else>Ron</p>

So let's say we have a variable called "name". If its value is equal to 'roger'. We will have name printed on screen "Roger" otherwise this condition will print name "Ron". We can make this condition longs as given below.

 //If variable name equals roger print name Roger
<p v-if='name=="roger"'>Roger</p>
//If variable name equals albert print name Albert
<p v-else-if='name=="albert"'>Albert</p>
//If variable name equals smith print name Smith
<p v-else-if='name=="smith"'>Smith</p>
//Else print Ron
<p v-else>Ron</p>

3.v-html & v-text

Another important directive. If you want to render HTML tags then this directive comes in use check here.

 //Variable with HTML tags in value
codeLine: '<div><h2>Some Content</h2></div>'

//printing variable using V-HTML
<div v-html="codeLine"></div>

//Output Will BE text without html tags
Some Content

//printing variable using V-text
<div v-text="codeLine"></div>

//Output Will BE text with html tags
<div><h2>Some Content</h2></div>


You might want to hide or show some data. And here we have v-show directive for this. It will hide the DOM element if false check example.

 //let's assume age = 15

//So this will print 
<div v-show="age < 15">You Are Not Allowed To Drink Alcohol</div>
//And this will be hidden
<div v-show="age > 15">You Are Allowed To Drink Alcohol</div>

5.v-if vs v-show

The main difference is that v-show hides DOM element if condition is not true. But v-if removes the HTML from the DOM instead of hiding it.


You will need to loop through data on some stage. Vue js has v-for which is a for loop. Usage example

 //let's say team has some playersplayers: ['Roger','Andrew','Duglus','Steve','Mark','Johnson']//So let's print name using loop v-for<ul>    <li v-for="(player,index) in players" :key="index"></li></ul>//this will print player listRogerAndrewDuglusSteveMarkJohnson

For more Vue JS Directives Check Vue Documentation here

So which VueJS directive you think is going to be used most by you and why. Let me know