Vue Events
Event handling in Vue is done with the v-on
directive, so that we can make something happen when for example a button is clicked.
Event handling is when HTML elements are set up to run a certain code when a certain event happens.
Events in Vue are easy to use and will make our page truly responsive.
Vue methods are code that can be set up to run when an event happens.
With v-on
modifiers you can describe in more detail how to react to an event.
Get started with events
Lets start with an example to show how we can click a button to count moose in a forest.
We need:
- A button
v-on
on the <button> tag to listen to the 'click' event- Code to increase the number of moose
- A property (variable) in the Vue instance to hold the number of moose
- Double curly braces
{{}}
to show the increased number of moose
Example
Click the button to count one more moose in the forest. The count property increases each time the button is clicked.
<div id="app">
<img src="img_moose.jpg">
<p>{{ "Moose count: " + count }}</p>
<button v-on:click="count++">Count moose</button>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
count: 0
}
}
})
app.mount('#app')
</script>
Try it Yourself ยป
Note: A benefit that comes with Vue is that the number of moose in the <p> tag is updated automatically. With plain JavaScript we would need to update the number the user sees with an additional line of code.
Events
There are lots of events we can use as triggers for running code, among the most common ones are: 'click', 'mouseover', 'mouseout', 'keydown' and 'input'.
For a complete list of events to use you can visit our HTML DOM Events page.
'v-on'
The v-on
directive allows us to create pages that respond to what the user does.
The Vue v-on
works by telling the browser what event to listen to, and what to do when that event occurs.
Methods
If we want to run more complex code when an event occurs we can put the code in a Vue method and refer to this method from the HTML attribute, like this:
<p v-on:click="changeColor">Click me</p>
Event Modifiers
In addition to v-on
and Vue methods we can use something called event modifiers to modify an event so that it for example only happens once after a page is loaded, or modify an event like 'submit' to prevent a form from being submitted.
Learn More
As we can see, there are three techniques we need to learn about to use events in Vue:
- The Vue
v-on
directive - Vue methods
- Vue
v-on
modifiers
Click 'Next' to continue this tutorial and learn more about these techniques for event handling.