<[object Object] defer="true" src="https://static.cloudflareinsights.com/beacon.min.js" token="0a1dcfae6c4348e2aa2d13c20d9fe61d">

# Directives

Vue.js provides a bunch of different directives out of the box for the developer's enjoyment and happiness. To me, these are awesome to work with because they can be sprinkled in the templates and bring this declarative approach to my code that makes it easy to reason about.

# Syntax

So, they are pieces of code you add to the markup as if you were adding attributes to your tags. Please note the following highlighted line of code:



 


<input
    type="text"
    v-model="message"
    />
1
2
3
4

You will see that our v-model directive starts with a v-. All of the directives in Vue have this same prefix.

Within the quotation marks, we pass in the values for the directives; in this case it is the variable message we want to bind to this input field.

They can also have arguments, which follow a : and you can see it is class in the following example:


 


<span
    v-bind:class="{colored: indent == 'spaces'}"
    >Color me surprised</span>
1
2
3

Pop Quiz!

What would be the value for the example above?

You got it, the object: {colored: indent == 'spaces'}. This means it could be defined elsewhere, for example inside the data key in the configuration object.

Another piece that you could come across when looking at directives is a modifier, for example:


 




<button
    v-on:click.prevent="doSomething"
    >
  Click me!
</button>
1
2
3
4
5

Where .prevent is actually calling event.preventDefault() for you. Handy, I told you 🎉!

You can write your own directives, but let's review that in another section. For now, we will start using them in our markup examples to build up more complex ones and explain other concepts. So make sure you get at least an overview of which ones exist off the shelf.

# Shorthand

There is a shorter way to write a couple of them.

So


 


<span
    v-bind:class="someClass"
> Some content</span>
1
2
3

Can also be found written as:


 


<span
    :class="someClass"
> Some content</span>
1
2
3

And


 


<input type="checkbox"
    v-on:click="doSomething">
My checkbox</span>
1
2
3

becomes:


 


<input type="checkbox"
    @click="doSomething">
My checkbox</span>
1
2
3

I actually prefer this syntax.

TIP

The official list of built-in directives which are available is here.

# Examples

Here is a pen with a few examples of built-in Vue directives in action:

See the Pen 01. Directives by @ackzell on CodePen.

Last Updated: 3/24/2022, 12:13:05 AM