What are directives in Vue.js?

Vue directives are special HTML element attributes that begin with the prefix v-. Directives tell the library to do something to a DOM element.

A directive can be written as:

<element prefix-directiveName="[argument:] expression [filters...]">
// code
</element>

For example:

<div v-text="Hi!" ></div>

Here, the prefix is v, the directive ID is text, and the expression is “Hi!”. This directive instructs Vue.js to update the div’s textContent.

Some directives require an argument before the expression. In the example below, the click argument indicates that we want the v-on directive to listen for a click event and then call the clickHandler method.

The directive accepts one argument, specified by the colon (:):

<template>
<a v-on:click="clickHandler">Click me!</a>
</template>
<script>
export default {
methods: {
clickHandler: function() {
alert('test')
}
}
}
</script>

In the above example, the click argument indicates we want the v-on directive to listen for a click event and then trigger the clickHandler method when the event happens.

A directive can be modified by modifiers that are specified by a dot (.).

For example:

<form v-on:submit.prevent="formSubmitted()"></form>

The .prevent modifier automatically calls formSubmitted() on the event. This prevents the form from causing a page to reload, which is the default behavior.

Free Resources