[Vuejs]-Iterate through Vue component fields

0๐Ÿ‘

I can see two ways to do this.

Provide a list of properties in an array, if you know it in advance (this is better practice as the data property gets initiated in the right way):

const props=['field1','field2', ...];
export default {
  async mounted(){
     //load the data and ensure only the expected properties are mounted
     //this avoids any unexpected behaviour.
     const result = await loadMyData();
     for(let prop of props) this[prop]=result[prop];
  }
  data(){
    //instantiate the data object to ensure all the properties are reactive
    const data={};
    for(let prop of props) data[prop]=null;
    return data;
  }
  methods:{
    async updateServer(){
       //build the data object to send back to the server then send it.
       const data={};
       for(let prop of props) data[prop]=this[prop];
       await sendUpdate(data);
    }
  }
}

The second way is to store a list of properties when you load the data from the server using Object.keys() and store this as a data property. You will then need to use vm.$set to ensure all of the properties have the correct reactivity, and you will not be able to have the properties at the root level, instead you will need to nest them (see the vue docs). However I assume that if your view object is designed to react to these properties then you must know them in advance.

0๐Ÿ‘

You could wrap your fields in a model field in your data:

data:{ model:{}}

Then on mounted you could set reactive props in your model

  mounted(){
        for(let field in YOUR_JSON_OBJ){
           Vue.set(this.model, field , YOUR_JSON_OBJ[field])
        }
   }

Then when you need to submit form, just pass your vue model prop

YOUR_SUBMIT_METHOD(JSON.stringify(this.model))

Leave a comment