driconmax
driconmax

Reputation: 942

VueJS Multiple level objects $SET

I'm trying to set the value of an object inside another with an input, but it doesn't work.

The objects starts empty in data

    data(){
        form: {}
    }

Then, in beforeMount, i fill the objects with n values in the first level, and other n values inside them (i don't know how many values neither their names)

    this.form: {
        s1: {
            name: 'test'
        },
        s2: {
            test: '123'
        }
    }

Finally, when i use an event or in the v-model to set the value, nothing happends. The input stays with the initial value.

I thought that this.$set might be the solution, but it only works if the object has only one level

    this.$set(this.form['s1'], 'name', 'New Value');

Basic example:

    <template>
        <q-input filled v-model="form['s1']['name']" label="Filled" />
    <script>
    
    export default {
      name: 'APP',
    
      components: {
        
      },
    
      data () {
        return {
          form: {},
        }
      },
      beforeMount() {
        this.form['s1'] = {};
        this.form['s1']['name'] = "Test";
      }
    }
    </script>

This is the basic minimum example running with quasar, but it happends also in vue-native(React-Native) using native-base's text inputs, and elementjs.

Upvotes: 1

Views: 578

Answers (1)

Ashwin Bande
Ashwin Bande

Reputation: 3063

You can use Object.assign in following way as described in documentation. It must be reactive.

export default {
      name: 'APP',
      components: {},
      data () {
        return {
          form: {},
        }
      },
      beforeMount() {
        this.form = Object.assign({}, this.form, {
             s1: {
                name: 'test'
              },
             s2: {
                test: '123'
              }
          });
        // this.form['s1'] = {};
        // this.form['s1']['name'] = "Test";
      }
    }
    </script>

Upvotes: 1

Related Questions