vuejs / Discussion

Vue.js discussion
167 stars 17 forks source link

How to check if a form has values for every input on every input change and then trigger a method? #475

Open noahmatisoff opened 8 years ago

noahmatisoff commented 8 years ago

I have a form that will be filled out by a user. Once the user has completed the form, I want to send an HTTP request to my API to get some data.

I'd prefer not to use v-on:click and include a button in the form, because the user may change around the inputs multiple times to see new data (and trigger the method with sends the HTTP request again), and I think it's a bad user experience to repeatedly click a button to get the new data.

How can I watch each individual input for changes and if there's a value for all of the inputs then send the HTTP request? I already have it implemented, but with a button to trigger the request, and that is what I'm trying to move away from.

Twiknight commented 8 years ago

try using $watch on each individual data.

noahmatisoff commented 8 years ago

Hey @Twiknight thanks, could you show me an example in code?

Twiknight commented 8 years ago

@matisoffn http://vuejs.org/api/#watch

noahmatisoff commented 8 years ago

So it works great with the code below:

watch: {
 'my.key': {
    handler: function(val, oldVal) {

    },
    deep: true
  }
}

However... The values of val and oldVal are identical when logging them to the console. Shouldn't oldVal be one step behind? Any idea what would cause this?

falco467 commented 7 years ago

Hi!

This is indeed documented behaviour: Vue.JS will only provide the old value for primitive data-types. For complex types Vue would have to copy the whole object before mutation, to give you the old state - this could get very expensive for big objects. - So you have to save the original value yourself (e.g. via JSON.stringify)