Vue Events

Vue Events

Interactivity on the web is driven by events.

Vue provides a seamless way to listen to standard DOM events like clicks, keypresses, and form submissions.

When an event occurs, Vue can execute your JavaScript code automatically.


Handling Events in Vue

In vanilla JavaScript, you would use addEventListener() to capture events.

In Vue, you use custom directives directly in your HTML templates.

This keeps your UI structure and its behavior closely tied together.


Inline Event Handlers

For very simple tasks, you can write JavaScript directly inside the event directive.

This is known as an inline event handler.

It is perfect for simple counters or boolean toggles.

Inline Handler Example:

<button @click="count++">
  Add 1
</button>
<p>Count is: {{ count }}</p>

Method Event Handlers

Writing long logic directly in the HTML template quickly becomes messy.

For complex logic, Vue allows you to call a method instead.

You simply provide the name of the function you wish to execute.

Method Handler Example:

<button @click="greetUser">Greet</button>

The Event Object

Sometimes you need to access the original DOM event object.

If you use a method handler, Vue automatically passes the event object as the first argument.

You can use this to access properties like event.target.value.


Exercise 1 of 1

?

When is it appropriate to use an inline event handler instead of a method handler?