The official documentation for VueJS event handling can be found here: VueJS Event Handling.
In this tutorial, we are going to look at how you can successfully handle events within your VueJS applications. This is by no means a replacement for the official documentation, think of it more so as a suplementary guide filled with live examples!
If you get through this I would love to hear your feedback either in the comments section or on twitter: @Elliot_F.
Being able to handle events in some manner is vital if you want to be able to make awesome real time applications with VueJS. Thankfully, VueJS allows us to handle events in a fairly easy fashion and this is just one of the reasons that I’m becoming a big fan of the framework!
A Simple Example
Let’s kick this tutorial off by dealing with a standard button click event. So initially we will need a
<button/> element, and a method defined in our Vue instance that we can then map to a
VueJS allows us to listen to these DOM events using the
counter = counter + 1. Not to a particular function but this will still work.
Our Vue instance for the above demo looks something like this:
v-on:click directive to point towards the name of our function like so:
The HTML for the above code looks something like so:
And the Vue instance that has been created features our newly referenced
update() function, this also subsequently logs
Hello World to your console. You can see this by opening up your browser’s console by right clicking and clicking
Say you wanted to add functionality on a certain key press event within your application, you could do this by using
keyup.key combined with the
v-on directive like so:
Let’s now create our Vue instance:
Now, Vuejs has aliased all of the most popular keys for us. This includes:
If you wish to use something outwith this list, then you will have to use the specific key code for that key. You can see the full list of key codes here: Mozilla Key Codes.
Let’s see this in action, try and enter a message into the input below and then click the
enter key. You should see an alert popup with the contents of the input.
So, in this tutorial, we covered how you can effectively handle events within your VueJS applications. Hopefully you enjoyed this! If you did then please let me know in either the comments section below or on twitter: @Elliot_F.