DEV Community

Cover image for Event Handling in Vue
mattiatoselli
mattiatoselli

Posted on

Event Handling in Vue

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>
Enter fullscreen mode Exit fullscreen mode

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!'
Enter fullscreen mode Exit fullscreen mode

The Double Click

    <div id="app">
        <button v-on:dblclick="handleDoubleClick">Pssst. Double click me ;)</button>
    </div>
Enter fullscreen mode Exit fullscreen mode

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....");
            }
          }
        })
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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.

Latest comments (0)