I have a dilemma with handling an array of objects in my Vue component. I am using v-for to display the objects, but now I want to update certain items in the array and save only those changes in a new object. Currently, when I attempt this by mapping over the items in the justAnotherSaveFunction method, all the items from the array are being saved instead of just the modified ones. To address this issue, I tried using @input on the <b-form-input>
. However, this approach is causing a new object to be added to the array with every keystroke. How can I adjust it so that objects are only pushed to the array when I click the save button?
Here is a snippet of the template:
<b-card-group columns>
<b-card v-for="item in items" :key="item.id" no-body>
<b-card-header>
Item {{ item.id }}
</b-card-header>
<b-card-body>
<b-form-group v-for="(value, index) in anotherItems.values" :key="index" class="form-group">
<span>{{ val }}</span>
<p>{{ item[val] }}</p>
<b-form-input v-model="item[value + '_change']" class="form-control" @input="(newValue) => addChangedValue(newValue, item.id)"></b-form-input>
</b-form-group>
</b-card-body>
</b-card>
</b-card-group>
<b-button variant="primary" @click="justAnotherSaveFunction">
Save
</b-button>
And here are the methods involved:
data(){
return{
items: [
{
id: 1
key: "something"
val: "somethng"
val_change: "somethhing"
},{id: 3
key: "something2"
val: "something2"
val_local: "something2"
},
],
anotherItems: {
{
"name":"Randome name",
"values":["val"],
}
},
changedValueArray: []
},
methods: {
addChangedValue(newValue, itemId) {
this.changedValueArray.push({ id: itemId, value: newValue})
},
justAnotherSaveFunction() {
console.log("objects\n" +JSON.stringify(this.changedValueArray))
const newData = this.items.map((item) => {
const newItem = {};
newItem.item_id = item.id;
this.anotherItems.values.forEach((val) => {
newItem[val] = item[`${val}_change`];
});
return newItem;
});
}
}