Open In App

Vue.js Event Modifiers

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:

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.

Project Structure

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.




<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.




<template>
  <center>
    <h1 style="text-align: center; 
        color: green">
            GeeksforGeeks
   </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


Article Tags :