As expected from any respectable Javascript framework, Vue provides a way to handle DOM events such as mouse movements, clicks, keystrokes, etc.
What is very interesting and enjoyable is the quick and easy way in which such events can be managed.
By using the v-on: syntax, and providing an handler method, we can handle events easily. Here are some example:
Handling click event
<div id="app">
<!-- `sayHello` is the name of a method -->
<button v-on:click="sayHello">Hi</button>
</div>
and of course the handler:
var example2 = new Vue({
el: '#app',
data: {
name: 'Vue.js'
},
// define methods under the `methods` object
methods: {
sayHello: function (event) {
// `this` inside methods points to the Vue instance
alert('Hello ' + this.name + '!')
// `event` is the native DOM event
if (event) {
//this will show the tag which fired the event
alert(event.target.tagName)
}
}
}
})
// you can invoke methods in JavaScript too
example2.greet() // => 'Hello Vue.js!'
The Double Click
<div id="app">
<button v-on:dblclick="handleDoubleClick">Pssst. Double click me ;)</button>
</div>
and this is the double click handler:
var app = new Vue({
el: '#app',
methods : {
handleDoubleClick : function() {
console.log("Hi, here we are dealing with a double click it seems....");
}
}
})
Handling the event object
We can obviously access the entire event as we saw in previously, by launching the event handler and passing the entire object like in vanilla javascript.
<button v-on:click="handleEvent($event)">We'll do it the old way</button>
Of course Vue provides a simple way to handle common tasks, like for example the preventDefault() function when we submit a form, here is the link to the official guide's paragraph.
Top comments (0)