Create New Post

Vue.js Event Listeners

In Vue.js, you can use the v-on directive to attach event listeners to elements. Event listeners in Vue.js allow you to respond to user interactions, such as clicks, keypresses, and more. Here's an overview of using event listeners in Vue.js:

1. Basic Event Handling:

Use v-on to attach an event listener to an element.

Example:

<button v-on:click="handleClick">Click me</button>

or using shorthand syntax:

<button @click="handleClick">Click me</button>

In this example, the handleClick method will be called when the button is clicked.

2. Passing Parameters to Event Handlers:

You can pass parameters to the event handler by using a method call.

Example:

<button v-on:click="handleClick('Button clicked!')">Click me</button>

In this case, the handleClick method will be called with the string parameter when the button is clicked.

3. Event Object:

You can access the event object inside the event handler method.

Example:

<button v-on:click="handleClick($event)">Click me</button>

In this example, the handleClick method will receive the event object as an argument.

4. Key Modifiers:

Vue.js allows you to use key modifiers to listen for specific key events.

Example:

<input v-on:keyup.enter="handleEnterKey">

In this example, the handleEnterKey method will be called when the "Enter" key is pressed.

5. Event Modifiers:

You can use event modifiers to control the behavior of event propagation and default actions.

Example:

<a v-on:click.stop="handleClick">Click me</a>

In this example, the stop modifier prevents the click event from propagating further.

6. Listening to Custom Events:

You can use v-on to listen to custom events emitted by child components.

Parent Component:

<child-component @custom-event="handleCustomEvent"></child-component>

Child Component (emitting the event):

this.$emit('custom-event', eventData);

In this example, the handleCustomEvent method in the parent component will be called when the custom event is emitted from the child component.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

94414