Clear VUE v-model data at once

Asked

Viewed 1,856 times

1

I have an instance of Vue in which I take values from a form to send by ajax, I would like to clean the data saved by the v-models at once after sending, this is possible?

new Vue({
el: '#app',
data: {
    campo1: "",
},
methods:{
    saveForm:function() {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                //document.getElementById("demo").innerHTML = this.responseText;
                alert(this.responseText);                   
            }
        };
        xhttp.open("POST", "helpers/get_campo.php", true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send(
            "campo1="+this.campo1
        );
            this.campo1 = "";
    }
}
  • Put your code that calls ajax sff. It’s inside the right component?

  • In real situation I have several field, I would like to clear them after calling the saveForm method().

2 answers

3


You will have to clear one by one, but one option is to put the form attributes inside the separate object in the data. So you access them by this.fields.campo1 etc.. and can iterate the object by clearing only the fields you want:

new Vue({
  el: '#app',
  data: {
    campo_xx: '',
    fields: {
      campo1:"",
      campo2:"",
    }
  },
  methods: {
    saveForm () {
      http.post(url, this.fields)
        .then(response => {
          limpaForm()
        })
    },
    limpaForm () {
      for (field in this.fields) this.fields[field] = ""
    }
  }
})
  • Cool your solution, Vue has nothing of himself even for this?

  • Not, at least as far as I know, it does not differentiate from objects in the scope this are data or not, literal or function...

0

You could do with the code below

for (field in this.object) this.object[field] = ''

But if you have an array, object or number in the scope, it will be replaced by string(' '). Solving this problem, you can do with the code below.

for(let value in this.object) {
        switch (typeof this.object[value]) {
            case 'string':
                this.object[value] = '';
                break;
            case 'number':
                this.object[value] = 0
                break;
            case 'object':
                  Array.isArray(this.object[value]) ? this.object[value] = [] : this.object[value] = {}
                break;
            default:

        }
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.