Vue v-on Directive

Vue v-on Directive

The v-on directive is the core tool used to listen to DOM events in Vue.

You attach it to an HTML element and specify which event you want to capture.

Once captured, it executes your specified JavaScript or Vue method.


The v-on Syntax

The full syntax requires writing v-on: followed by the event name.

For example, capturing a click event looks like v-on:click.

Capturing a keyup event looks like v-on:keyup.

Full Syntax Example:

<button v-on:click="doSomething">
  Click Me
</button>

The @ Shorthand

Because listening to events is so common, typing v-on: repeatedly can be tedious.

Vue provides a convenient shorthand for v-on:.

You can simply replace v-on: with the @ symbol.

This makes your HTML templates much cleaner and easier to read.

Shorthand Example:

<!-- Full syntax -->
<button v-on:click="doSomething"></button>

<!-- Shorthand syntax --> <button @click="doSomething"></button>


Listening to Different Events

You are not limited to just click events.

You can use v-on (or @) to listen to any standard DOM event.

Examples include @mouseover, @mouseout, @submit, and @scroll.

The flexibility of v-on allows you to build highly dynamic user interfaces.


Exercise 1 of 2

?

What is the primary function of the v-on directive in Vue?

Exercise 2 of 2

?

What symbol is used as the standard shorthand for the v-on directive?