7tacos
7tacos

Reputation: 39

Vuejs cannot push to nested array

First question on stack overflow, I apologize if I am asking in the wrong place. New to Vue and been trying for several days to finish a small project. I've simplified it but here it is. I want to be able to enter as many customer names as I need, and then be able to add as many customer's childrens names as I need. So an array of customers with a nested array of children. I can get the customers to add, but I cannot figure out why I cannot push a new element into the children's array. Here is my code.

new Vue ({
el: '#app',
data: function () {
    return {
            formdata: [],
            fields: [{
                name: '',
                childs: [{
                    cname: '',
                }]
            }],
        };
    },
    methods: {
        addRow: function() {
            this.fields.push({
                name: "",
                childs: [{
                    cname:'',
                }],
            });
        },
        addChild: function() {
            this.child.push({
            });
        },
    },
});

And my html

<div id="app">
  <button class="btn btn-success" @click="addRow">Add</button>
    <div v-for="field in fields" >
      <div class="input-group">
        <input type="text" placeholder="Name" class="form-control" v-model="field.name">
      </div>
      <div v-for="child in field.childs" >
        <div class="input-group">
          <input type="text" placeholder="Child" class="form-control" v-model="child.cname">
          <div class="input-group-btn">
            <button class="btn btn-success" @click="addChild">Add</button>
          </div>
        </div>
      </div>
    </div>
  </div>

Again, the problem is that i can push a new "name" to the fields array, but i cannot push a new child into the fields child array. I have been trying every permutation of child childs field fields etc, trying to find how to reference that array. Any help would be greatly appreciated!

Upvotes: 2

Views: 1409

Answers (1)

thanksd
thanksd

Reputation: 55644

In your addChild method, you need to be accessing the childs property of the relevant field. Currently, you are trying to access the childs property of the Vue instance, which doesn't exist.

You should pass the relevant field to the addChild method like so:

<button class="btn btn-success" @click="addChild(field)">Add</button>

And then update your addChild method to reference the childs array of the field passed in:

addChild: function(field) {
  field.childs.push({});
}

Upvotes: 2

Related Questions