Modifying instance data while ajax submit, reverts input data

148 Views Asked by At

I have the following method on my Vue instance:

    ajaxSubmit: function(event) {
        this.loader = true;

        var form = event.target;

        var action = form.getAttribute('action');
        var data = new FormData(form);
        var method = form.getAttribute('method').toUpperCase();

        this.$http({
            body: data,
            method: method,
            url: action
        }).then(function(response) {
            if (response.body.alerts) {
                response.body.alerts.forEach(function(alert) {
                    this.alerts.push(alert);
                }.bind(this));
            }

            this.loader = false;
        }, function(response) {
            // same as success callback
        });
    }

Let's say I have an input with a default value of "Test". If I update it to "Test111" and then submit. The value reverts to "Test". The submitted value is correct, as "Test111" gets saved to my database and also after a refresh, the input has the correct value.

I managed to narrow down the problem. I observed that it only happens if in the ajaxSubmit method I change data on the instance. For example if I delete the lines:

this.loader = true;
this.loader = false;
this.alerts.push(alert);

everything works as expected.

Also, if an input is bound to the instance via v-model, it doesn't revert its value.

So, in the end I guess I found the source of the problem, but I don't understand it, and I can't solve it.

Any help would be greatly appreciated!

1

There are 1 best solutions below

4
On

The problem you are having is that Vue re-renders the input element after the submit and because you have set a value attribute it will always re-render with the initial value. The way to get around this is to either not have an initial value, in which case Vue will keep the content, or to use v-model and bind it to data:

HTML

<input type="text" name="test" v-model="inputVal" />

JavaScript

...
data:{
  ...
  inputVal: "Test"
  ...
}
...

Here's your updated JSFiddle: https://jsfiddle.net/v3xx02n9/1/