Complete Vue.js Course: Mastering from Basic to Advanced
Sobre a Aula

Using v-on to Listen to Events

 

Hello, students! Welcome to Lesson 2 of Event Handling in Vue.js. Today, we will learn how to use the v-on directive to listen to events.

Recap

In the previous lesson, we learned what events are and how they are essential for event handling. We also learned the basic syntax of the v-on directive.

What is the v-on directive?

The v-on directive allows associating an event with a method. The v-on directive is one of the most important directives in Vue.js.

How to Listen to Events with v-on

To listen to events with the v-on directive, we use the following syntax:

<element v-on:event="method">

Where:

  • event is the name of the event you want to listen to.
  • method is the method that will be called when the event occurs.

Example

Let’s see an example of how to use the v-on directive to listen to the click event and activate a button:

<button v-on:click="activateButton">Activate</button>

In the example above, the activateButton() method will be called when the user clicks the button.

JavaScript Expressions in the v-on Directive

You can use JavaScript expressions in the v-on directive to determine whether the event should be listened to or not.

For example, let’s see an example of how to use the v-on directive to listen to the click event only if the button is disabled:

<button v-on:click="activateButton" v-bind:disabled="disabled">Activate</button>

In the example above, the activateButton() method will only be called if the disabled attribute is false.

Conclusion

The v-on directive is a powerful tool that can be used to listen to events and respond to user actions and system events.

In the next lesson, we will learn how to create and call methods in response to events.

Entrar na conversa
Rolar para cima