简体   繁体   English

Vue 将新项目添加到 object 属性的数组中

[英]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 :我使用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.没关系,但现在我想在campaign.adGroups中添加一个新项目,但它似乎不起作用。

I have used the $set function to add new items to the array but it doesn't work.我已经使用$set function 将新项目添加到数组中,但它不起作用。

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

How can I handle this case in VUE?我如何在 VUE 中处理这种情况?

Thank you!谢谢!

When adding an element to an array, $set isn't needed, you can use the .push method:向数组添加元素时,不需要$set ,您可以使用.push方法:

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM