In Vue.js, the v-on directive is used to attach event listeners to DOM elements.
It allows us to listen for and respond to DOM events triggered by user interactions, such as "clicks", "mouse movements" and "keyboard inputs".
Here's an overview of v-on directives:
<button v-on:click="handleOnClick">Click me</button>
the "v-on:click" directive attaches a click event listener to the button element.
When the button is clicked, the "handleOnClick" method defined in the Vue instance will be called.
<button @click="handleOnClick">Click me</button>
Vue.js provides a shorthand syntax for "v-on", using the "@" symbol.
The above example is equivalent to the previous one and attaches a click event listener to the button element.
<button @click="handleOnClick('arg1', 'arg2', 'arg3')">Click me</button>
We can pass arguments to the event handler function by specifying them inside the event listener expression.
when the button is clicked, the "handleOnClick" method will be called with 'arg1', 'arg2' and 'arg3' as arguments.
<ul @click="handleOnItemClick"> <li v-for="item in items"> {{ item }} </li> </ul>
We can use event delegation by attaching event listeners to parent elements and handling events for multiple child elements.
a click event listener is attached to the "
<button @click.stop="handleClick">Click me</button>
above syntax will prevent the click event from propagating further.
<a href="http://www.example.com" @click.prevent="handleClick"> @click.prevent have updated default behaviour of anchor tag </a>
This prevents the default behaviour of the anchor tag, which is to navigate to the specified link.
<!-- stop the click event's propagation --> <a @click.stop="stop the default behaviour of click event "></a> <!-- stop from default behaviour and stopPropogation doing in chained --> <a @click.stop.prevent="stop the default behaviour and propagation"></a> <!-- form submit event will no longer reload the page wjile submitting form --> <form @submit.prevent="onSubmit"></form> <!-- only trigger event handler if event.target is the element itself not from child or sibling element--> <div @click.self="trigger event when element itself">...</div>
The "v-on" directive in Vue.js provides a powerful way to handle DOM events and interact with user inputs.
It allows us to create interactive and responsive user interfaces by listening for and responding to user actions.