Vue.js Directives

Vue.js directives are special tokens in the template that tell the library to do something to a DOM element. They come with a special v- prefix to indicate that they are special attributes provided by Vue.js. Directives are an essential feature of Vue.js, enabling dynamic and reactive data binding, conditional rendering, list rendering, event handling, and more. In this topic, we will cover Vue.js directives in detail, from basic to advanced concepts, with examples and explanations.

What are Vue.js Directives?

Directives are special tokens in Vue.js that attach special behavior to the DOM. They are prefixed with v- to indicate they are special attributes provided by Vue.js. Directives bind data to the DOM, listen to events, or modify the DOM in response to data changes. Understanding directives is key to leveraging the full power of Vue.js.

Vue.js Directives

Basic Directives

v-bind

The v-bind directive dynamically binds one or more attributes, or a component prop, to an expression.

				
					<div id="app">
  <a v-bind:href="url">Visit Vue.js</a>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{url:'https://vuejs.org'}})</script> 
				
			

Explanation:

  • v-bind:href="url" binds the href attribute to the url data property.
  • The output will be a clickable link directing to https://vuejs.org.

v-model

The v-model directive creates a two-way binding on form input elements.

				
					<div id="app">
  <input v-model="message">
  <p>{{ message }}</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{message:'Hello Vue!'}})</script> 
				
			

Explanation:

  • v-model="message" binds the input value to the message data property.
  • As you type in the input field, the paragraph updates in real-time.
  • The output will be
				
					<input value="Hello Vue!">
<p>Hello Vue!</p>

				
			

v-on

The v-on directive is used to listen to DOM events.

				
					<div id="app">
  <button v-on:click="greet">Greet</button>
</div> <script type="litespeed/javascript">new Vue({el:'#app',methods:{greet:function(){alert('Hello Vue!')}}})</script> 
				
			

Explanation:

  • v-on:click="greet" listens for the click event and calls the greet method.
  • Clicking the button shows an alert saying “Hello Vue!”.
  • The output will be
				
					<button>Greet</button>

				
			

Conditional Directives

v-if, v-else-if, v-else

These directives control the conditional rendering of elements.

				
					<div id="app">
  <p v-if="type === 'A'">Type A</p>
  <p v-else-if="type === 'B'">Type B</p>
  <p v-else>Other Type</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{type:'A'}})</script> 
				
			

Explanation:

  • v-if, v-else-if, and v-else control which paragraph is rendered based on the type data property.
  • The output will be
				
					<p>Type A</p>

				
			

v-show

The v-show directive toggles the visibility of an element without removing it from the DOM.

				
					<div id="app">
  <p v-show="isVisible">I am visible</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{isVisible:!0}})</script> 
				
			

Explanation:

  • v-show="isVisible" controls the visibility of the paragraph.
  • The output will be
				
					<p style="display: block;">I am visible</p>

				
			

List Rendering

v-for

The v-for directive is used to render lists of items by iterating over arrays or objects.

				
					<div id="app">
  <ul>
    <li v-for="item in items" :key="item.id">{{ item.text }}</li>
  </ul>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{items:[{id:1,text:'Learn JavaScript'},{id:2,text:'Learn Vue'},{id:3,text:'Build something awesome'}]}})</script> 
				
			

Explanation:

  • v-for="item in items" iterates over the items array.
  • :key="item.id" is used to track each item’s identity.
  • The output will be
				
					<ul>
  <li>Learn JavaScript</li>
  <li>Learn Vue</li>
  <li>Build something awesome</li>
</ul>

				
			

Event Handling

v-on

The v-on directive is used to listen to DOM events.

				
					<div id="app">
  <button v-on:click="greet">Greet</button>
</div> <script type="litespeed/javascript">new Vue({el:'#app',methods:{greet:function(){alert('Hello Vue!')}}})</script> 
				
			

Explanation:

  • v-on:click="greet" listens for the click event and calls the greet method.
  • The output will be
				
					<button>Greet</button>

				
			

Event Modifiers

Event modifiers are used to handle common event-related tasks like stopping propagation and preventing default behavior.

				
					<div id="app">
  <button v-on:click.stop="greet">Greet</button>
  <form v-on:submit.prevent="onSubmit">
    <button type="submit">Submit</button>
  </form>
</div> <script type="litespeed/javascript">new Vue({el:'#app',methods:{greet:function(){alert('Hello Vue!')},onSubmit:function(){alert('Form submitted')}}})</script> 
				
			

Explanation:

  • v-on:click.stop="greet" stops the click event from propagating.
  • v-on:submit.prevent="onSubmit" prevents the form from submitting.
  • The output will be buttons that trigger alerts without propagating or submitting.

Form Input Bindings

v-model

The v-model directive creates a two-way binding on form input elements.

				
					<div id="app">
  <input v-model="message">
  <p>{{ message }}</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{message:'Hello Vue!'}})</script> 
				
			

Explanation:

  • v-model="message" binds the input value to the message data property.
  • The paragraph updates in real-time as you type.
  • The output will be
				
					<input value="Hello Vue!">
<p>Hello Vue!</p>

				
			

Modifiers for v-model

Modifiers allow fine-tuning of v-model behavior.

				
					<div id="app">
  <input v-model.trim="message">
  <p>{{ message }}</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{message:''}})</script> 
				
			

Explanation:

  • v-model.trim="message" trims the input value.
  • The output will be a trimmed input displayed in real-time.

Attribute Binding

v-bind

The v-bind directive dynamically binds one or more attributes, or a component prop, to an expression.

				
					<div id="app">
  <a v-bind:href="url">Visit Vue.js</a>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{url:'https://vuejs.org'}})</script> 
				
			

Explanation:

  • v-bind:href="url" binds the href attribute to the url data property.
  • The output will be a clickable link directing to https://vuejs.org.

Class and Style Bindings

v-bind:class

The v-bind:class directive dynamically binds one or more classes to an element.

				
					<div id="app">
  <p v-bind:class="{ active: isActive }">Hello Vue!</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{isActive:!0}})</script> 
				
			

Explanation:

  • v-bind:class="{ active: isActive }" binds the active class to the isActive data property.
  • The output will be
				
					<p class="active">Hello Vue!</p>

				
			

v-bind:style

The v-bind:style directive dynamically binds one or more inline styles to an element.

				
					<div id="app">
  <p v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }">Hello Vue!</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{activeColor:'red',fontSize:30}})</script> 
				
			

Explanation:

  • v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }" binds the color and fontSize styles to the respective data properties.
  • The output will be
				
					<p style="color: red; font-size: 30px;">Hello Vue!</p>

				
			

Registering a Global Custom Directive

Custom directives in Vue.js Directives can be registered globally to extend Vue’s functionality.

				
					<div id="app">
  <p v-highlight="'yellow'">Highlight me!</p>
</div> <script type="litespeed/javascript">Vue.directive('highlight',{bind:function(el,binding){el.style.backgroundColor=binding.value}});new Vue({el:'#app'})</script> 
				
			

Explanation:

  • Vue.directive('highlight', { ... }) registers a global custom directive named highlight.
  • el.style.backgroundColor = binding.value sets the element’s background color.
  • The output will be
				
					<p style="background-color: yellow;">Highlight me!</p>

				
			

Registering a Local Custom Directive

Custom directives can also be registered locally within a Vue instance.

				
					<div id="app">
  <p v-highlight="'yellow'">Highlight me!</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',directives:{highlight:{bind:function(el,binding){el.style.backgroundColor=binding.value}}}})</script> 
				
			

Explanation:

  • directives: { highlight: { ... } } registers a local custom directive named highlight.
  • The output will be the same as the global directive example:
				
					<p style="background-color: yellow;">Highlight me!</p>

				
			

Advanced Directives

v-pre

The v-pre directive skips compilation for this element and all its children.

				
					<div id="app">
  <span v-pre>{{ raw }}</span>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{raw:'This will not be compiled'}})</script> 
				
			

Explanation:

  • v-pre tells Vue to leave the {{ raw }} interpolation uncompiled.
  • The output will be
				
					<span>{{ raw }}</span>

				
			

v-cloak

The v-cloak directive keeps the element cloaked until the Vue instance finishes compiling.

				
					<div id="app">
  <p v-cloak>{{ message }}</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{message:'Hello Vue!'}})</script> <style>[v-cloak] {
  display: none;
}</style>
				
			

Explanation:

  • v-cloak hides the element until Vue’s compilation is complete.
  • The output will be
				
					<p>Hello Vue!</p>

				
			

v-once

The v-once directive renders the element and component once and skips future updates.

				
					<div id="app">
  <p v-once>{{ message }}</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{message:'This will not change'}})</script> 
				
			

Explanation:

  • v-once renders the message once and does not update it.
  • The output will be
				
					<p>This will not change</p>

				
			

In this topic, we explored Vue.js directives in-depth, from basic to advanced concepts. Vue.js directives are powerful tools for building dynamic and reactive applications. They allow you to bind data, handle events, conditionally render elements, iterate over lists, and even create custom behaviors. By mastering these directives, you can harness the full potential of Vue.js to build robust and efficient web applications.Happy coding !❤️

Table of Contents