In this post, we will learn and take a look at the built-in directives provided by the Vue.js framework, and we will also learn to create and use our own custom-made Vue directive.
Directives are attributes that you can link with the DOM elements, prefixed by the clause “v-” which helps to know the library that it is a special type of syntax used for performing some tasks. Directives are usually used for direct manipulation of DOM. Some of the most used and famous directives are “v-if”, “v-for”, and “v-show”.
The directives are used to apply effects on DOM elements but reactively. Let’s understand it with an example:
In the above tag, the “v-if” is a directive that will delete or add the paragraph tag “<p>”, depends on the “showText” variable’s truthiness.
Similarly, we have the “v-show” directive which can perform the same functionality described above:
The subtle difference between “v-if” and “v-show” is that “v-if” does not render the element while loading the page if the bound variable is not true and it loads when the variable becomes true. In contrast, “v-show” will render the element at the web page’s load time but hides it. So, “v-if” is time effective at the page’s load time and time-consuming when the variable gets true. It has to render the whole element while “v-show” is time effective upon the truthiness of the variable time-consuming at the load time of the web page.
Alright! Let’s have a look at a directive that takes the argument.
Another most widely used directive is “v-bind,” which is used for interacting and updating the HTML attributes. For example, if we want to bind some variable to the “href” attribute of the <a> tag, we can bind the “href” attribute like this:
Just like the “v-bind” directive, Vue provides a “v-on” directive for binding the variable for listening to the events fired in the DOM. For example, for listening to the Click event and binding some variable to it, the syntax would go like this:
In the inverted commas, we can provide the expression as well as functions.
We have learned about the directives in Vue and see how to use the directives in Vue.js. We have discussed some of the most used and basic built-in directives of Vue.js, which helps a lot and saves a huge amount of time in the development.