I am having trouble editing items that are created by Vue, it always gets the wrong index of the item to replace when I am editing. I understand that Vue cannot react to certain changes like array length so I am using the methods suggested in the Vue docs
However these are not working either. I suspect it has something to do with my setup. Please see below.
NB
- myData is an Object sent through as a prop.
- This code works perfectly when pulling through data from an API (ie on static data where the index has not changed)
- The object of the code below is to:
- Add a child to an array
- Edit that child by:
- finding the childs index by its' id
- replacing that child with a new object with the edited data
- currently the index of any added children is always 0 so it replaces the first child object in the array and not itself
- The result is emitted to the main vue app, where it updates the myData value in Data, and feeds the data down to the children components via props
Adding an item
methods: {
localSave() {
const myLocalData = this.myData
const myChildrenLength = myLocalData.children.dependents.length
const myChildren = {
'id': myChildrenLength + 1,
'fullName': this.childsFullName,
'gender': this.childsGender,
'dateOfBirth': this.childsYearOfBirth,
'parentage': this.childsParentage,
'isFinanciallyIndependent': this.childsDependency
}
Vue.set(myLocalData.children.dependents, myChildrenLength, myChildren);
localStorage.setItem('myData', JSON.stringify(myLocalData));
this.$emit('send-local-data', myLocalData);
}
}
Editing an item
methods: {
localEditSave() {
const myLocalData = this.myData;
const myChild = {
'id': this.childsId,
'fullName': this.childsFullName,
'gender': this.childsGender,
'dateOfBirth': this.childsYearOfBirth,
'parentage': this.childsParentage,
'isFinanciallyIndependent': this.childsDependency
}
const arrayPath = myLocalData.children.dependents;
let removeIndex = arrayPath.map(function(item) { return item.id; }).indexOf( myChild.id );
Vue.set(arrayPath, removeIndex, myChild);
console.log('localEditSave removeIndex = ', removeIndex)
localStorage.setItem('myData', JSON.stringify(myLocalData));
this.$emit('send-local-data', myLocalData);
},
}