Hi @ozne I am waiting for a meeting so I took the time to scratch the idea for both methods. Not ideal code but could give you an idea.
Method 1: compare original and current formData
<template>
<form @submit.prevent="handleSubmit()">
<p>
name: <input type="text" required v-model="currentFormData.name">
</p>
<p>
email: <input type="email" required v-model="currentFormData.email">
</p>
<p>
<button type="submit">Submit</button>
</p>
<hr>
<pre>{{ changedFormData }}</pre>
</form>
</template>
<script>
export default {
name : 'MethodOneForm',
props : {
formData : { type : Object, default : () => ({}) }
},
data () {
return {
currentFormData : { ...this.formData },
originalFormData : { ...this.formData },
};
},
computed: {
changedFormData () {
return Object.keys( this.currentFormData ).reduce( ( formData, field ) => {
if ( this.currentFormData[ field ] !== this.originalFormData[ field ] ) {
formData[ field ] = this.currentFormData[ field ];
}
return formData;
}, {} );
},
},
methods : {
handleSubmit () {
if ( Object.keys( this.changedFormData ).length === 0 ) {
alert( 'No changes' );
return;
}
console.log( 'submit', this.changedFormData );
},
},
};
</script>
Method 2: keep track of changed fields using events
<template>
<form @submit.prevent="handleSubmit()">
<p>
name: <input type="text" required v-model="currentFormData.name" @input="handleChange('name')">
</p>
<p>
email: <input type="email" required v-model="currentFormData.email" @input="handleChange('email')">
</p>
<p>
<button type="submit">Submit</button>
</p>
<hr>
<pre>{{ changedFormData }}</pre>
</form>
</template>
<script>
export default {
name : 'MethodTwoForm',
props : {
formData : { type : Object, default : () => ({}) }
},
data () {
return {
currentFormData : { ...this.formData },
changedFields : [],
};
},
computed : {
changedFormData () {
return this.changedFields.reduce( ( formData, field ) => {
formData[ field ] = this.currentFormData[ field ];
return formData;
}, {} );
},
},
methods : {
handleSubmit () {
if ( this.changedFields.length === 0 ) {
alert( 'No changes' );
return;
}
console.log( 'submit', this.changedFormData );
},
handleChange ( changedField ) {
const results = this.changedFields.filter( ( field ) => field !== changedField );
if ( this.currentFormData[ changedField ] !== this.formData[ changedField ] ) {
results.push( changedField );
}
this.changedFields = results;
},
},
};
</script>
Hope it helps
EDIT:
Improved the MethodTwoForm handleSubmit method guard clause to use the changedFields array. As I copied and pasted from MethodOneForm I missed that.
Also, here is the view I used to test them:
@extends('layouts.app')
@section('content')
<method-one-form :form-data="{name:'Rodrigo'}"></method-one-form>
<method-two-form :form-data="{name:'Rodrigo'}"></method-two-form>
@endsection