Son Le
Son Le

Reputation: 314

Vue add new items to array of an object property

I have an array like this:

campaigns = [
    {id: 1, adGroups: [{id: 1, title: 'Hello'}, {id: 2, title: 'Hello'}]},
    {id: 2, adGroups: [{id: 3, title: 'Hello'}, {id: 4, title: 'Hello'}]},
];

I render the array using v-for:

<fieldset class="mb-3 p-3 rounded border" v-for="(campaign, index) in campaigns" :key="index">
    <fieldset class="mb-3 p-3 rounded border" v-for="(campaignAdGroup, indexAdGroup) in campaign.adGroups" :key="indexAdGroup">
        {{ campaignAdGroup.title }}
    </fieldset>
</fieldset>

It's fine, but now I want to add a new item to the campaign.adGroups, but it seems it doesn't work.

I have used the $set function to add new items to the array but it doesn't work.

this.$set(this.ruleCampaigns[index].adGroups, this.ruleCampaigns[index].adGroups.length, {id: null, title: ''})

How can I handle this case in VUE?

Thank you!

Upvotes: 2

Views: 895

Answers (1)

Dan
Dan

Reputation: 63059

When adding an element to an array, $set isn't needed, you can use the .push method:

new Vue({
  el: "#app",
  data() {
    return {
      campaigns: [
        {id: 1, adGroups: [{id: 1, title: 'Hello'}, {id: 2, title: 'Hello'}]},
        {id: 2, adGroups: [{id: 3, title: 'Hello'}, {id: 4, title: 'Hello'}]},
      ]
    }
  },
  methods: {
    add(index) {
      const campaign = this.campaigns[index];
      const groups = campaign.adGroups;
      groups.push({ id: groups.length + 1, title: 'Hello' });
    }
  }
});
<div id="app">
  <fieldset class="mb-3 p-3 rounded border" v-for="(campaign, index) in campaigns" :key="index">
    <fieldset class="mb-3 p-3 rounded border" v-for="(campaignAdGroup, indexAdGroup) in campaign.adGroups" :key="indexAdGroup">
      {{ campaignAdGroup.title }}
    </fieldset>
    <button @click="add(index)">Add</button>
  </fieldset>
</div>

<script src="https://unpkg.com/vue"></script>

Upvotes: 2

Related Questions