|

Vue JS Directives

Vue JS Directives

Let’s take a closer look at directives in this VueJS directives tutorial. Directives are the part part of Vue that attach special meaning and behavior to plain html elements on the page. The directive is like a token which indicates to Vue that it has special control and access to this particular DOM element. Directives are also a part of other view layer front end frameworks, however most web developers have found the concept of directives easier to work with in Vue than say Angular. Directives are really one of the foundations of understanding Vue, so let’s look closer at them now.


Vue JS Directive vs Component

What is the difference between a vue js directive vs component? Well, I like to think of the directive as a more granular entity that modifies the behavior of basic html elements in the dom. Components on the other hand are more so relating to sections or widgets on the page. Components are like putting together a larger piece of data and behavior together. Therefore, it is more important to be 100% comfortable with directives first, then move on to components when you’re ready.


It all starts with v-model

The v-model directive is really the bread and butter of getting started with Vue. In fact every other directive we look at in this tutorial also somehow makes use of v-model in the same markup. You can apply a v-model directive to an <input>, <select>, <textarea>, or a component. It’s use creates a two way binding between the element and the data attribute it refers to in the Vue JavaScript code.

Try it: Change up the text in the text box.

directives used: v-model


Displaying an element conditionally using v-show

Consider you have a text area where a user can type to send a message. Initially, that text area will be blank of course. If there is no text to be sent, well then maybe we should not provide a button for which to try and send that message. If the user begins typing some text however, it now makes sense to provide a button to send that text. We can do this in Vue using the v-show directive. Try typing some text in the text area here:

Now, use the backspace key to clear out any text. Neat, right?! Here is how we do it.

directives used: v-model, v-show

v-show Summary: When an element in the page has a v-show directive, it means that entire element can be conditionally displayed based on the truthiness of the data property it is bound to in Vue. If the data property is truthy, the element is displayed. If the data property is falsy, the element is not displayed.

note: An element with v-show will always be rendered and remain in the DOM as v-show just toggles the display CSS property of the element.


Using v-if and v-else together in Vue

v-if is a little more powerful so to speak than v-show. Whereas v-show only toggles css to change visibility, v-if will render or not render an element in the dom based on the condition being tested. Here, we will make use of a v-if and v-else together, so that we can change the message being presented to the user based on what they have typed in the text area.

directives used: v-model, v-if, v-else, v-show

This makes pretty good sense, right? If there is no message – tell the user to enter some text, else, message must have some text – so tell them to click the button to send. So we use v-if and v-else to determine which <h2> element to display, and v-show to toggle the display of our button. Very cool!


Using v-if, v-else-if, and v-else together in Vue

Vue also offers a v-else-if directive that can be used much like you would use else-if clauses in native JavaScript or other programming languages. The previous sibling element must make use of a v-if or v-else-if in order to work properly. Let’s see an example.

directives used: v-model, v-if, v-else-if, v-else


Using template v-if to toggle several elements at one time

If you have a situation where you need the ability to render or remove multiple elements at one time, you can do this by applying the v-if directive to a wrapping <template> element. Let’s see it in action here.

directives used: v-model, v-if, v-show

In this example we wrap the elements we want to render or remove from the DOM with a <template> element, which has a v-if directive. Now, the v-if behavior affects all wrapped elements inside the template. This can be very handy.


Creating a list with Range v-for

The v-for directive can accept a number to loop over. Whatever dom element v-for is attached to, will be repeated as many times as the number used in the v-for dictates. For example, if you wanted to render a list that is 5 items long, you can do so like this.

directives used: v-for

You can also apply this technique to tables if you like.

directives used: v-for


Loop over an array with v-for

One thing you see in VueJS all the time is the concept of having an array of data in your Vue instance, and using a v-for directive in the html markup to display all items contained in the array. Then, if items get added to, or taken away from the data arrray – the html list updates in real time. You can almost think of it like a for loop that never stops running. In actuality, it is not always running but what happens is due to the reactivity everything re renders if there is any change at all to the underlying data. Here we loop over a very basic array.

directives used: v-for


Loop over an Object with v-for

As we know in JavaScript, a simple object is made up of key / value pairs. You might also refer to the key as a property more formally. Let’s see how to loop over an Object while getting access to the property and value of the Object being iterated over.

directives used: v-for


Loop over an array of objects with v-for

This example expands on the idea of a songs array. Instead of having one string per index in the array, we populate each index of the array with an object that represents a song. Each of these objects has two properties, a name and an artist. When we then loop over the array of objects we can use dot notation to access the value we are looking for, i.e., song.artist and song.name. The example makes use of vue js directive params in the v-for, like this: v-for=”(song, index) in songs”

directives used: v-for

Note that since we used the index in the v-for loop, we are able to access the current iteration as the list renders out. Since it is 0 based, we simply used index + 1 to make our numbers start from 1.


Attaching Event Listeners with v-on

The v-on directive is used to attach an event listener to a particular element. We talked a bit about events in vue already. In other words, to listen to DOM events you can use the v-on directive. The type of listener that gets implemented is determined by the argument which is passed to it. Of course the most commonly used event listener is the click event, and in Vue it looks like this:

  • <button v-on:click=”doSomething”></button>

Let’s see an example of the v-on:click directive in action here.

directives used: v-on:click

Here we set up two event listeners, one for each button. When the user clicks the first button, the addOne function in the methods object gets called. When the user clicks the second button, the resetCount function gets called in the methods object. Very nice! You can also use the shorthand version if you like. It does the same thing, but it is less typing, and who doesn’t like less typing?! It looks like this:

  • <button @click=”doSomething”></button>

In addition to v-on:click, the more commonly used v-on directives are v-on:keyup and v-on:submit.


Using v-text for interpolation

In addition to using standard interpolation using the mustache braces between html elements, you can also use the special Vue directive v-text to set the textContent of an html element. In the following example we are going to build a calculator that makes use of many of the directives we have looked at so far, in addition to making use of the v-text directive.

directives used: v-model.number, @click, v-model, @click.prevent, v-text, v-show

This example makes some interesting uses of the various directives we have covered so far in addition to some new ones. When the page first loads we have num1 set to 10, num2 set to 20, the operator set to addition, and the result set to 30. Typically, you’ll set all your default data values in the data object so that something displays on initial render. Now, the first thing we notice is that if we click in one of the inputs to change a number or change the operator, instantly the = sign and result disappear. This is due to the directive of @click=”result = ”” that we have assigned to each input in the form which sets the result variable to an empty string. Now, the = operator in our markup is inside of a v-show like so <span v-show=”result”>=</span>. If the result variable is not truthy, then we will not show the = operator. Additionally, we make use of the v-text directive in our markup like so <span class=”text-success” v-text=”result”></span> which is the equivalent of <span class=”text-success”>{{ result }}</span>. So the equals sign, and the result of the operation are never displayed if the result variable is not truthy. You’ll also note that each <input> uses a v-model.number directive, which means we expect an actual number value – not a string from this input. The <select> tag also makes use of a v-model and you can see how that translates into selecting which operation to use in the example. Finally, we notice that the button makes use of a @click.prevent directive which instructs the button to *not* submit the form on click. Fantastic!


Flexible data binding with v-bind

Early on we talked about v-model and how it creates a data binding between Vue and the html on the page, usually used on <input>, <select>, or <textarea> elements. With v-bind, you have a whole slew of ways to bind data to the DOM. It can be used to bind image source attributes, to dynamically bind different classes to an element, bind styles, bind an object of attributes, and many more. This tutorial is getting pretty epic in length, so we’ll just look at one more example using the v-bind directive.

directives used: v-bind

This example is a really cool example of turning a Bootstrap Card into a component in Vue. There is a fair amount happening in this example, but the main demonstration here is how we are binding a custom data object to a Vue component so we can easily create our own cards by simply putting a <card> tag on the page. With our component set up, we display three different cards on the page, each having it’s own data within it thanks to the unique data object bound to each card via the v-bind directive.


Vue JS Directives Summary

Wow! That was a pretty epic dive into using directives in VueJS. Remember, directives are special attributes beginning with the v- prefix assigned to html in a Vue powered page to give them special powers. As a quick recap, here are some of the directives we looked at, and a super concise summary of each one.

  • v-model
  • v-show – used to conditionally display an element (css based)
  • v-if – used to conditionally render an element
  • v-else-if – serves as an “else if block” for v-if and can be chained multiple times
  • v-else – displays an element when v-if evaluates to false
  • v-for – iterate over a range, an array, an object, or an array of objects
  • v-on – listen to various DOM events (click, keyup, submit, etc..)
  • v-bind – used to dynamically bind one or more attributes, or a component prop, to an expression
  • v-text – same as {{ interpolation }} and updates the element’s textContent