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.
Lets start with an example to show how we can click a button to count moose in a forest.
We need:
v-on
on the <button> tag to listen to the 'click' event{{}}
to show the increased number of mooseClick 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.
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.
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.
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>
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.
As we can see, there are three techniques we need to learn about to use events in Vue:
v-on
directivev-on
modifiersClick 'Next' to continue this tutorial and learn more about these techniques for event handling.
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!