Vue.js is a progressive javascript framework for developing web user interfaces. It is a performant, approachable, and versatile framework. We can create Single Page Applications as well as Full Stack applications. It is built on top of HTML, CSS, and Javascript which makes it easier for developers to integrate Vue.js in any application at any stage.
Vue.js Event Modifiers help to ignore the common event handling like don’t reload the page when the form is submitted and other similar issues. Event Modifiers allow to handle them in the DOM itself. We don’t need to create any new components for these purposes.
Vue.js Event Modifiers:
- .stop: The propagation of the click event will stop.
- .prevent: This is used to prevent the reloading of the webpage.
- .self: This is used to tell the element to trigger the event if the target element is itself.
- .capture: This is used to handle the event of the inner element before the inner element handles it.
- .once: This is used to trigger the event once.
- .passive: This is used for touch events to improve performance.
Syntax: The event modifiers are directive postfix, which means they act on some action. We have a click action and we want the event modifier to stop reloading as follows:
<form @submit.prevent="submitted"></form>
Example: In the following example, we have a form with an input element. We have used the event modifier to stop reloading of the webpage and then called the function to pass the submitted values.
Step 1: Create a new Vue.js project with the npm node.js package manager using the following command.
npm init vue@latest
Enter the project name and preset the project as follows:
Project Structure: After successful installation, the following project structure will be formed.
Step 2: In the script section of the App.vue, add a data variable called search which will store the input value and declare a method that will be called when the form will be submitted.
App.vue
<script> export default { data() { return { search: "" , }; }, methods: { submitted(e) { this .search = e.target[0].value; }, }, }; </script> |
Step 3: In the template section of the App.vue, create a form with an input element and a submit button.
App.vue
<template> <center> <h1 style= "text-align: center; color: green" > neveropen </h1> <strong> Vue.js Event Modifiers </strong> <br /> </center> <center> <form @submit.prevent= "submitted" > <input type= "text" name= "search" placeholder= "Search Tutorials" /> <button type= "submit" >Submit</button> </form> <p>Submitted value: {{ search }}</p> </center> </template> |
Step 4: Run the project using the following command and see the output.
npm run dev
Output: On successfully building the project, open http://localhost:3000, and the result will be as follows.
Reference: https://vuejs.org/guide/essentials/event-handling.html#event-modifiers