[Vuejs]-How to refactor repetitive attributes in Vue.js

2👍

You can listen for the change event on the form tag itself instead of listening on the individual inputs.

<form @change="doSomething"> will run the function doSomething() when something inside the form has changed eg: if you type in an input and release focus

In the doSomething function, you want to find out what element changed. We get this info from the event parameter provided from the input event:

methods: {
  doSomething(event) {
    this.lastEvent = event.target.value;
  }
}

You can see this in effect on this Codepen example

If the form element is a child of an element inside a component like so:

<template>
  <div>
    <form></form>
  </div>
</template>

the @changeevent-listener will not work as there is nothing that changes on the root element (div) on the component.

In this case, we need to add the .native modifier, like so: @change.native="doSomething".

Leave a comment