Table of contents
1.
Introduction
2.
Types of directives
2.1.
v-show directive
2.2.
v-if, v-else, v-else-if directives
2.3.
v-bind
2.4.
v-model
2.5.
v-on
2.5.1.
Event modifiers
2.5.2.
Shorthand syntax
3.
Arguments
4.
Dynamic Arguments
5.
Modifiers
6.
FAQs
7.
Key takeaways
Last Updated: Mar 27, 2024

VueJS: Directives

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Vue.js essentially combines the basic idea of Angular and React. One such idea inspired by AngularJs is directives. Directives are instructions or say, chunks of code to be used in HTML which gives instructions to Vue.js. It helps to manipulate the HTML or create dynamic attributes in Vue.

There are several built-in directives in Vue.js, along with the option to register our custom directives. This article will primarily discuss the important built-in directives in Vue.

Types of directives

Some of the most used inbuilt functions are v-show, v-model, v-bind v-if, v-on, v-for, and v-html. We will discuss the most important inbuilt directives one by one in detail:

v-show directive

The v-show directive is used to either show or hide various HTML elements based on a condition. It can thus be used to hide/show any function with the following syntax:

<element v-show="flag/condition">
	// main code
</element>


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

All three of these directives allow creating conditional HTML elements and work on if, else, or else if conditions from js. This code is conditionally rendered in Vue Instead of being returned in HTML.

<p v-if="condition"></p>


v-else renders the element when v-if comes out to be false. The syntax for v-else is:

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


In case there are multiple conditions to be checked and compared, we can use v-else-if with other directives such as v-if and v-else. The syntax for this directive is:

<element v-else-if="varible/ (true/false) / expression">
	// content
</element>

It is essential to have the v-if directive right before v-else or v-else-if, or else the directive wouldn’t work.
 

Example: Creating a program for calculating result.

<html>
  <body>
    <div class="app">
      <h1></h1>
      <div v-if="marks < 10">
        <h1>Keep it up</h1>
      </div>
      <div v-else-if="marks > 10 && marks < 20">
        <h1>Average Result </h1>
      </div>
      <div v-else>
        <h1>Excellent Result</h1>
      </div>
    </div>
    <script>
      export default {
        name: "Show",
        data() {
          return {
            marks: 15
          };
        }
      };
    </script>
  </body>
</html>


Output:

v-bind

v-bind primarily binds the value from the component logic or the model to HTML. This means that the model updates the HTML view and the view updates the data model. This is called “one-way-binding” in Vue and is done by v-bind. The syntax for v-bind is:

<element v-bind:property="anyValue">
	// content
</element>


Example: For v-bind could be binding an image source to the src property of that given image using this directive. However, this would not work both ways and the value will not be reflected the other way round.

<html>
    <head>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <p> v-bind directive example</p>
        <div id="app">
            <button v-on:click="ifActive=!ifActive"> Click here </button>
            <h1 v-bind:class="{active: ifActive, error: !ifActive}">Coding Ninja's </h1>
        </div>
        <script>
            var app = new Vue({
                el: '#app',
                data: {
                    ifActive: true
                }
            })
        </script>
    </body>
</html>


Output:

v-model

The v-model directive is a way for Vue to allow data, props and properties to be passed into a Vue component. This type of binding is a “two-way-binding”, allowing the view(HTML) and the model to interact with each other

Example: We will use an example where we will get a value from a textbox and show that value at the same time:

<html>
    <body>
        <div class="app">
            <h1></h1>
            <div>
                <input v-model="Name" />
            </div>
            <br />
            <div> Your Full Name Is : </div>
        </div>
        <script>
            export default {
                name: "Model",
                data() {
                    return {
                        Name: ""
                    };
                }
            };
        </script>
    </body>
</html>


Output:


v-on

This executes functions on both standard js events and custom events. The function name is put within quotes and the event type is specified after a colon.

Example:

<html>
    <body>
        <h1>V-on example</h1>
        <button v-on:click="buttonToClick">Click Here</button>
        <script setup>
            function buttonToClick() {
                alert('Button clicked!')
            }
        </script>
    </body>
</html>


Output:

The buttonToClick is a component function executed by clicking the button element attached to the directive. A browser pop-up alert will read, “Button clicked!”

Event modifiers

Event modifiers on v-on directive can be chained to the events and change how they are executed. These are essentially used to save time so that the user doesn’t have to multiple lines of code in JavaScript. Some event modifiers in Vue are:

  • self: The event won’t trigger until the target is exactly the same element holding the directive.
  • prevent: This straight-up stops the event taking place.
  • stop: It does not let the event propagate.
  • once: It allows the event to take place only once:
     
<template>
	<button v-on:click.once="toClick">Click Here</button>
</template>
//rest of the code


Shorthand syntax

The v-on directive does have a shorthand syntax too. The correct syntax would be replacing ‘v-on:’ with ‘@’, leading to the same behavior as v-on:click.once

<template>
	<button @click.once="toClick">Click Here</button>
</template>
//rest of the code

Arguments

Directives that can take "arguments" denoted by a colon after the directive include v-bind, v-on etc. 

V-bind, for example, can reactively update HTML attributes:

<a v-bind:href="url"> ... </a>

The argument here will be href, making the directive bind the href attribute of the element to the url value.
 

The v-on directive can also take arguments as it listens to DOM events. For example:

<a v-on:click="performTask"> ... </a>

Dynamic Arguments

We can also wrap directive arguments in square brackets if we wish to use js expressions in them. This can be done by:

<a v-bind:[randomAttribute]="url"> ... </a>


Here, the evaluated value for ‘randomAttribute’ will be used as the argument’s final value. This implies that ‘randomAttribute’ is dynamically evaluated as a js expression.

Dynamic arguments can also be used to bind handlers and dynamic event names. Example:

<a v-on:[event1]="performTask"> ... </a>

Modifiers

Modifiers are postfixes that indicate if directives must be bound in a special way. They are denoted by a dot such as the .prevent modifier. It tells v-on to call event.preventDefault() when the event is triggered:

<form v-on:submit.prevent="onSubmit">...</form>


There are several more examples of modifiers in Vue, v-model being another important one, for example.

FAQs

1. What is the difference between v-bind and v-model directives?
Vue.js has a framework that follows a model-view-modelview. The data here is the model, while the HTML is the view. v-bind only provides one-way data binding, while v-model provides a two-way data binding that allows the view and model to interact both ways.
 

2. What does v-text directive do?
The v-text directive provides a one-way binding. It basically binds the value of data variables to the Vue template. The syntax for this directive is: 

<element v-text="data variable">  
	//body
</element>


3. What is the directive pattern in Vue JS?
The directive pattern followed throughout Vue.js whenever directives are being used is:

<element prefix-directive="[argument:] ( keypath |  expression ) [filters]">
	//body
</element>

Key takeaways

We learned about directives in Vue JS, their various types, syntax and examples. Along with the types of directives, we also discussed arguments, dynamic arguments and modifiers while giving suitable examples to provide a deep understanding of the concept.

You can go to Coding Ninjas Studio to try and solve more problems for practice. Share this blog with your friends if you found it helpful! Until then, All the best for your future endeavours, and Keep Coding.

Live masterclass