Event Handling with v-on

In the previous lesson we learned about some of Vue’s most used directives, such as v-if or v-model. There are more directives, but the last one we will learn for now is v-on.

We can use v-on to handle user input by listening to events such as click or change. To do so, we need to pass the type of event that we want to listen to as well as the function we want to call when the event is triggered. In this case we listen to the click event and call a method named bye, which has to be defined on our Vue instance.

<button v-on:click="bye">Say bye</button>

And here is how to modify our example from the previous lessons so we display a button that let’s us say goodbye to our friends.

<div id="app">
  <ul>
    <li v-for="friend in friends">{{ greeting }} {{ friend }}!</li>
  </ul>

  <button v-on:click="bye">Say goodbye</button>
</div>

<script src="https://unpkg.com/vue@2.4.1/dist/vue.js"></script>

<script>
  let app = new Vue({
    el: '#app',
    data: {
      greeting: 'Hello',
      friends: [
        'Alice',
        'Bob',
        'Dave',
        'Monica'
      ]
    },
    methods: {
      bye () {
        this.greeting = 'Bye'
      }
    }
  })
</script>

As you can see, we have included a button and used the v-on directive to handle a click event. The other new thing here is the declaration of the bye() method. Just as we can declare data on the Vue instance, we can also declare methods.

Note that there is a shorthand for defining event handlers:

<button @click="bye">Say goodbye</button>

It’s up to you which one to use, but we recommend sticking to just one of the options throughout your project for consistency.

We will look at more examples for methods a little later in the course when we talk about computed properties. For now we will continue with one of Vue’s most important features: Components.

comments powered by Disqus