Events

Event Handling

Events can be triggered by various actions with the most popular being clicking a button. Let's say we have a button:

<button>Increment</button>

And we store a count in a variable:

const app = Vue.createApp({
  data() {
    return {
      counter: 0
    }
  }
});

To "listen" to a click event, we're using the `v-on` directive:

<button v-on:click="counter += 1">Increment</button>

"v-on" shorthand

The `v-on` directive we use to listen to the click event can be replaced with its "shorthand":

<button @click="counter += 1">Increment</button>

Event Handling with a method

<button v-on:click="incrementCounter">Increment</button>

`incrementCounter` is a method that we define in our Vue instance:

const app = Vue.createApp({
  data() {
    return {
      counter: 0
    }
  },
  methods: {
    incrementCounter() {
      this.counter += 1;
    }
  }
});

We're using `this` to access the `counter` variable, because we're inside a method and not inside the `data` object.

Passing a parameter

Say we display a list of cities and we want to show the country of the current selection:

<div v-for="capital in capitals" :key="capital.name" @mouseOver="selectedCountry(capital.country)">
	{{ capital.name }}
</div>

Here we're using the `@mouseOver` event to call the `selectedCountry` method. We're passing the country as a parameter:

const app = Vue.createApp({
  data() {
    return {
      ...,
      selectedCountry: '',
      capitals: [
        { name: 'London', country: 'UK' },
        { name: 'Paris', country: 'France' },
        { name: 'Berlin', country: 'Germany' },
        { name: 'Rome', country: 'Italy' },
        { name: 'Madrid', country: 'Spain' },
        { name: 'Buenos Aires', country: 'Argentina' }
      ]
    }
  },
  methods: {
    selectedCountry(country) {
      this.selectedCountry = country;
    }
  }
});

Other events

There are many other events that can be triggered, such as:

  • click
  • mouseover
  • keydown
  • keyup
  • submit
  • change
  • input
  • focus
  • blur
  • load
  • scroll
  • resize
  • error
<img :src="image" @mouseover="addBorder">