Introduction to Vue Events
So far we have seen how Vue.js reacts to changes in our data and updates the DOM accordingly, based on our template. But how can we react to DOM events, such as when a user clicks a button? Obviously we want users to be able to interact with our web application, and events are a central part of that.
With that, it’s time to introduce a new directive, namely the v-on directive. The v-on directive attaches an event listener to an element and takes the event type as an argument. The directive’s expression can either be the name of a method or an inline expression as we saw in the previous article.
The simplest example I can think of is probably showing an alert in response to clicking a button. I have already added a button to the template (see the JSFiddle at the bottom), but right now it doesn’t do anything. I’ll just quickly add a method which triggers an alert.
new Vue({
el: '#app',
methods: {
clickedButton: function() {
alert("You clicked the button!");
}
}
});
Now we are ready to connect the two pieces and trigger the click event. First I enter the name of the directive on the element within the template, which is v-on.
<button v-on>Click here!</button>
Then a colon and an argument with the name of the event that we would like to listen to. In this case, we are interested in the click event.
<button v-on:click>Click here!</button>
The expression is the name of our method; clickedButton in this case.
<button v-on:click="clickedButton">Click here!</button>
With this, we should see an alert whenever we click the button.
In the next article, we will see how we can pass arguments to an event handler.
Here is what you will learn:
- How to build advanced Vue.js applications (including SPA)
- How Vue.js works under the hood
- Communicating with services through HTTP
- Managing state of large applications with Vuex
- ... and much more!
