Listening to user events is an integral part of any responsive web app, and Vue apps are no exception. Vue comes built with a simple and efficient way to handle events with its v-on directive.

What Is Event Binding in Vue?

Event binding is a Vue.js feature that allows you to attach an event listener to a Document Object Model (DOM) element. When an event occurs, the event listener triggers an action or response in your Vue app.

You can achieve event-binding in Vue with the v-on directive. This directive allows your app to listen for user events like click, enter, or key-up events.

To attach an event listener to an element using v-on, add the event name as a parameter to the directive:

        <html>
<head>
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
  <div id="app">
    <button v-on:click="counter++">Click me</button>
    <p>{{ counter}}</p>
  </div>
  <script>
  const app = Vue.createApp({
    data() {
      return {
        text: 'Vue is awesome!',
        counter: 0
      }
    }
  })

  app.mount('#app')
  </script>
</body>
</html>

The code block above shows an example of a Vue app that listens to a click event. The code block uses a button to increment the counter value in the data property of the Vue instance by one.

The above code block binds the JavaScript expression counter++ to the button's click event with the v-on directive. Vue uses the @ character as a shorthand in place of the v-on directive due to v-on's frequent usage:

        <button @click="counter++">Click me</button>

Event binding in Vue is not limited to click events. Vue handles other events, like key press events, mouseover events, and more.

To bind any of these events to the v-on directive, replace the click event with the name of the desired event:

        <button @keydown.enter="counter++">Click me</button>

The code above sets up an event listener on the button that listens for the keydown event. When any key is pressed while the button has focus, Vue evaluates the counter++ expression.

Linking Events With Methods in Vue

In most Vue apps, you can handle more complex logic based on specific events occurring. Events and methods work hand-in-hand to perform app actions based on an event.

The methods property in Vue's Options Object holds important functions that your Vue app needs for enhanced reactivity. With the methods property in Vue, you can handle complex logic based on events.

Here's an example of a Vue app that shows events handled by the methods property:

        <html>
<head>
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
  <div id="app">
    <button @click="increment">Add 1</button>
    

    <button @click="reduce">reduce 1</button>
    <p>{{ counter }}</p>
  </div>
  <script>
    const app = Vue.createApp({
      data() {
        return {
          text: 'Vue is awesome!',
          counter: 0
        }
      },
      methods: {
        increment(){
          this.counter = this.counter + 1
        },
        reduce() {
          this.counter = this.counter - 1
        }
      }
    })
    app.mount('#app')
  </script>
</body>
</html>

The Vue app above depicts how to link events with methods. The app has two buttons that users can click to increment or reduce the counter value in the data property.

The app achieves this with the @click directive. The @click directive points to the functions in the methods property to manipulate the counter value.

When linking an argument to the click event, you can customize the increment and reduce methods to add or reduce the counter value based on the argument you pass to the method.

Like so:

        <body>
  <div id="app">
    <button @click="increment(5)">Add 5</button>
    

    <button @click="reduce(3)">reduce 3</button>
    <p>{{ counter }}</p>
  </div>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          text: 'Vue is awesome!',
          counter: 0
        }
      },
      methods: {
        increment(num){
          this.counter = this.counter + num
        },
        reduce(num) {
          this.counter = this.counter - num
        }
      }
    })

    app.mount('#app')
  </script>
</body>

This code block extends on the previous Vue app to allow the passing of arguments to the methods linked to the click event listener on the button.

The methods increment and reduce in the Vue instance take an argument num to increase or reduce the counter property.

This example shows how you can work with arguments when linking methods with events in Vue. Linking methods with events can help in making Vue apps more interactive.

Exploring the Prevent and Stop Modifiers in Vue

Event modifiers in Vue allow you to create better event listeners that cater to the specific needs of your application. To utilize these event modifiers, you chain the modifiers to events in Vue.

For example:

        <form @submit.prevent="handleSubmit">
  <input type="text" v-model="text">
  <button type="submit">Submit</button>
</form>

The code block above chains the prevent modifier to the submit event. The prevent modifier is commonly used when working with forms in Vue.

The prevent modifier's purpose is to prevent the default behavior of form submission, which is to reload the page. Using prevent, Vue can continue its processes while the handleSubmit method takes care of the form submission.

Another example of a very useful modifier is the stop event modifier. The stop event modifier stops an event from propagating further up the DOM tree.

Usually, an HTML child element's event bubbles up through the DOM tree, activating any event listeners attached to parent elements. You can prevent this event propagation with the stop modifier and prevent the event from triggering further event listeners.

To understand how the stop modifier stops the propagation of events further up a DOM tree, consider the code block below:

        <body>
    <div id="app">
        <div @click="outerClick" class="outer">
            <div @click.stop="innerClick" class="inner">
              <button @click="buttonClick" class="button">Click me</button>
            </div>
        </div>
    </div>
    <script>
    const app = Vue.createApp({
        methods: {
            outerClick() {
                console.log('Outer click')
            },
            innerClick() {
                console.log('Inner click')
            },
            buttonClick() {
                console.log('Button click')
            }
        }
    });

    app.mount("#app");
    </script>
 </body>

The code block above has three event listeners attached to three different elements. The button element is inside the div with the inner class, while the div with the inner class is inside the div with the outer class.

Each of the three elements listens for a click event and logs to the console, the name of the HTML element clicked. Below is additional class CSS styling to make the above code block easier to understand:

        <head>
    <style>
    .outer {
      padding: 20px;
      background-color: black;
    }
    .inner {
      padding: 20px;
      background-color: gray;
    }
    button {
      padding: 10px;
      background-color: white;
      border: 2px solid black;
      font-size: 16px;
      font-weight: bold;
      cursor: pointer;
    }
    </style>
</head>

On running the program, the created Vue app will look like this:

Vue app with a black and white click me button

Note that when you click the button, the program calls the buttonClick method and logs a message to the console. The program also calls the innerClick method.

However, the program does not call the outerClick method because the code block added a stop modifier to the innerClick event listener. This stops the event from propagating further up the DOM tree.

Without the stop modifier, the program will call the buttonClick method when you click the button, and the event will continue propagating up the tree, reaching the innerClick method and then the outerClick method.

Handling Events in Web Apps

You've learned how to use event binding in Vue to attach event listeners to elements and how to call methods when events occur. You've also understood how to use event modifiers to customize event behavior.

Web apps rely on some form of user events to carry out functions. JavaScript comes inbuilt with a lot of methods to capture and handle a variety of these events. These events help in building interactive apps.