2

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!

11
  • Have you tried this.ruleCampaigns[index].adGroups.push({id: null, data: {bid: ''}})? Commented Feb 25, 2021 at 8:50
  • 1
    @LucasMarcondesPavelski Yes, I have tried but doesn't work as well. Commented Feb 25, 2021 at 8:57
  • @shob When I add new item, the UI should display one more element, but it doesn't. Commented Feb 25, 2021 at 9:18
  • @shob Yes, it doesn't display the added item. Commented Feb 25, 2021 at 9:21
  • Yeah, That's sample code only, I just changed the question. Tks Commented Feb 25, 2021 at 9:27

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.