Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue how to detect form input changes

In my vue-app I have a form, which should detect each change. I tried to use @change and also with a watcher, but with no luck...

form: {
  name: "",
  surname: "",
  email: "",
},
changed: false

then in my template:

<form @change="hasChanged">

Then my watcher and method:

watch: {
    form: {
        handler: function(v) {
            return this.hasChanged();
        },
        deep: true
    }
},
methods: {
  hasChanged(){
    this.changed = true
  }
}

But this doesn't work.... what am I doing wrong?

like image 983
ST80 Avatar asked Apr 21 '26 14:04

ST80


1 Answers

Form element does not have a change listener. Consider binding each input instead with the onChanged event instead.

From what I am seeing, it seems like you want to know if the form has been edited. In that case you can try this

<template>
    <form>
        <input v-model="form.first_name"/>
        <input v-model="form.last_name"/>
        <input v-model="form.email"/>
    </form> 
</template>

<script>
    const defaultForm = {
        first_name: '',
        last_name: '',
        email: '',
    }  
    export default {
      data () {
        return {
            // form: defaultForm
            // edit
            form: {...defaultForm}
        }
      },
      computed: {
        hasChanged () {
          return Object.keys(this.form).some(field => this.form[field] !== defaultForm[field])
        }
      }
    }
</script>
like image 88
Babacar C. DIA Avatar answered Apr 23 '26 05:04

Babacar C. DIA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!