Clear VUE v-model data at once

1

I have a Vue instance in which I get values from a form to send via ajax, I would like to clear the data saved by the v-models at once after sending, is it 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 = "";
    }
}
    
asked by anonymous 17.01.2018 / 18:56

2 answers

3

You will have to clean one by one, but one option is to put the form's attributes inside a separate object in data . Thus, you access them by this.fields.campo1 etc ..., and you can iterate the object by cleaning 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] = ""
    }
  }
})
    
17.01.2018 / 19:07
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 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:

        }
    }
    
20.09.2018 / 23:45