The v-on directive in Vue instructs the browser, much like event handling in standard JavaScript:
which event—such as “click,” “keydown,” “mouseover,” etc.—to pay attention to
How to handle that situation if it arises
Examples using v-on
To show how v-on may be used with various events and different code to run when these events occur, let’s look at a few samples.
Let’s look at a few examples to demonstrate how v-on may be used with different events and different code to run when these events occur.
onclick Event
We can take action in response to predefined events with the v-on directive.
To take action when the element is clicked, use v-on:click.
Example
The <button> element uses the v-on directive to listen for the ‘click’ event. The yellow <div> behind the lightbulb is either visible or hidden depending on whether the ‘click’ event causes the ‘lightOn’ data property to be toggled between ‘true’ and ‘false’.
oninput Event
To take action when an element receives input—such as a keystroke inside a text field—use v-on:input.
Example
Determine how many keystrokes were made in an input text field:
{{ 'Input events occured: ' + inpCount }}
mousemove Event
To take action when the mouse pointer passes over an element, use v-on:mousemove.
Example
Whenever the mouse pointer passes over a <div> element, its background color can be changed:
Move the mouse pointer over the box below
Use v-on in a v-for Loop
The v-on directive can also be utilized within a v-for loop.
Every iteration within the v-on value has access to the array’s items.
Example
Show a list based on the food array, and then add a click event to each item such that it can modify the image’s source by using a value from the array item.
{{ food.name }}
Shorthand for v-on
‘@‘ is the shorthand for ‘v-on‘.
Example
Here, ‘@‘ is used in place of ‘v-on‘:
A bit later in this course, we will begin using the @ syntax.